Reputation: 165
I'm trying to check, if an user entered a number in a valid format. But it seems, that invalid String are also parsed with success. An example:
final String value1 = "12,85", value2 = "128,598.77";
NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
format.parse(value1); // ok
format.parse(value2); // ok, but it's not german format
Why does format.parse(value2) don't throw an exception?
Upvotes: 3
Views: 700
Reputation: 44965
Indeed the method parse
won't throw any exception in this case so you should provide a ParsePosition
and check that this index
has been set to the end of the String
indicating that the entire String
has been parsed successfully instead of only the beginning.
ParsePosition parsePosition = new ParsePosition(0);
format.parse(value1, parsePosition); // ok
System.out.println(parsePosition.getIndex() == value1.length());
parsePosition = new ParsePosition(0);
format.parse(value2, parsePosition); // ok, but it's not german format
System.out.println(parsePosition.getIndex() == value2.length());
Output:
true
false
Upvotes: 2
Reputation: 7928
Taken from java API
public abstract Number parse(String source, ParsePosition parsePosition)
Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, Long.MAX_VALUE] and with no decimals), otherwise a Double. If IntegerOnly is set, will stop at a decimal point (or equivalent; e.g., for rational numbers "1 2/3", will stop after the 1). Does not throw an exception; if no object can be parsed, index is unchanged!
It's an expected behaviour, the result will be 128.598
Upvotes: 3