2

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?

Armand
  • 23,463
  • 20
  • 90
  • 119
stebeg
  • 155
  • 2
  • 12

2 Answers2

3

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

Community
  • 1
  • 1
SCouto
  • 7,808
  • 5
  • 32
  • 49
2

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
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • Great idea. Thanks – stebeg Jun 14 '16 at 05:18
  • You could also use `System.out.println(parsePosition.getErrorIndex() == -1)` – rasmusgude Jun 11 '18 at 12:10
  • @rasmusgude you should try to call `parsePosition.getErrorIndex()` in both case, you will get `-1` even with `value2` which is not what is expected – Nicolas Filotto Jun 11 '18 at 12:22
  • @NicolasFilotto thanks for the update. You are absolutely right, nevermind my comment. Do you know why `getErrorIndex()` is not valid? The documentation states otherwise that and value `12345TEST` seem to behave as expected (getErrorIndex != -1) – rasmusgude Jun 11 '18 at 12:31
  • @rasmusgude because the parser doesn't consider it as a parsing error, it simply ignores `.77` and returns `128.598` – Nicolas Filotto Jun 11 '18 at 12:43