I'm using DecimalFormat
to parse / validate user input. Unfortunately it allows characters as a suffix while parsing.
Example code:
try {
final NumberFormat numberFormat = new DecimalFormat();
System.out.println(numberFormat.parse("12abc"));
System.out.println(numberFormat.parse("abc12"));
} catch (final ParseException e) {
System.out.println("parse exception");
}
Result:
12
parse exception
I would actually expect a parse exception for both of them. How can I tell DecimalFormat
to not allow input like "12abc"
?
From the documentation of
NumberFormat.parse
:Here is an example that should give you an idea how to make sure the entire string is considered.
Output:
Use the
parse(String, ParsePosition)
overload of the method, and check the .getIndex() of the ParsePosition after parsing, to see if it matches the length of the input.