简体   繁体   中英

Java - NumberFormat parsing invalid String with success

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?

Taken from java API

public abstract Number parse(String source, ParsePosition parsePosition)

Returns a Long if possible (eg, 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; eg, 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM