简体   繁体   English

Java-NumberFormat成功解析无效的字符串

[英]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. 但是看来,无效的String也会成功解析。 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? 为什么format.parse(value2)不会引发异常?

Taken from java API 取自Java API

public abstract Number parse(String source, ParsePosition parsePosition) 公共抽象数字解析(字符串源,ParsePosition parsePosition)

Returns a Long if possible (eg, within the range [Long.MIN_VALUE, Long.MAX_VALUE] and with no decimals), otherwise a Double. 如果可能,返回一个Long(例如,在[Long.MIN_VALUE,Long.MAX_VALUE]范围内,并且不带小数),否则返回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). 如果设置了IntegerOnly,则将在小数点处停止(或等价;例如,对于有理数“ 1 2/3”,将在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 这是预期的行为,结果将是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. 的确,在这种情况下, parse方法不会引发任何异常,因此您应该提供一个ParsePosition并检查此index是否已设置为String的末尾,指示整个String已成功解析,而不仅仅是开始。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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