简体   繁体   English

NumberFormat Java的奇怪行为

[英]Strange behaviour of NumberFormat Java

I have the following code to parse a String variable called str. 我有以下代码来解析一个名为str的String变量。

NumberFormat formatter = NumberFormat.getInstance();
Number number = formatter.parse(str);

I want to catch the Exception thrown when str is not a number just to validate it. 我想捕获当str不是一个数字时抛出的异常只是为了验证它。 The problem I have is that it does't always throws the ParseException expected. 我遇到的问题是它并不总是抛出预期的ParseException。 When the String str starts with a number but then are characters it seems to get a the first characters of the String and parse them as a number. 当String str以数字开头但后来是字符时,它似乎得到字符串的第一个字符并将它们解析为数字。

For example: 例如:

  • if str="a10" then is thrown a ParseException 如果str =“a10”则抛出ParseException
  • if str="10a" then no exception thrown and number=10 如果str =“10a”则没有抛出异常且number = 10

I cannot use Double.parseDouble(str) because str can have commas and points like 1,000.98 and this format is not understood by this method. 我不能使用Double.parseDouble(str),因为str可以有逗号和点,如1,000.98,这种方法不能理解这种格式。

Why is this happening? 为什么会这样? Can I validate it in any other way? 我可以用其他方式验证吗? Thanks 谢谢

If you look at the API , it clearly says: 如果您查看API ,它会清楚地说:

Parses text from the beginning of the given string to produce a number. 从给定字符串的开头解析文本以生成数字。 The method may not use the entire text of the given string. 该方法可能不使用给定字符串的整个文本。

If you want to see how far the parser parsed, you can use the other position-aware method . 如果要查看解析器解析的距离,可以使用其他位置感知方法 This way you can check if you have any trailing chars. 这样你就可以检查你是否有任何尾随的字符。 You could also check the whole string for alphanumeric chars using for instance common langs isAlpha . 你也可以使用常见的langs isAlpha检查整个字符串中的字母数字字符。

The behaviour is not strange, it's as designed 这种行为并不奇怪,它是按照设计的

Parses text from the beginning of the given string to produce a number. 从给定字符串的开头解析文本以生成数字。 The method may not use the entire text of the given string. 该方法可能不使用给定字符串的整个文本。

You may use the position-aware parsing method like this: 您可以使用这样的位置感知解析方法:

public static double parse(String str) throws ParseException {
  NumberFormat formatter = NumberFormat.getInstance();
  ParsePosition position = new ParsePosition(0);
  Number number = formatter.parse(str, position);
  if (position.getIndex() != str.length()) {
    throw new ParseException("failed to parse entire string: " + str, position.getIndex());
  }
  return number.doubleValue();
} 

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

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