3

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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

Great idea. Thanks
You could also use System.out.println(parsePosition.getErrorIndex() == -1)
@rasmusgude you should try to call parsePosition.getErrorIndex() in both case, you will get -1 even with value2 which is not what is expected
@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 because the parser doesn't consider it as a parsing error, it simply ignores .77 and returns 128.598

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.