为什么DecimalFormat允许字符作为后缀?

bla*_*666 15 java formatting

我正在使用DecimalFormat解析/验证用户输入.不幸的是,它在解析时允许字符作为后缀.

示例代码:

try {
  final NumberFormat numberFormat = new DecimalFormat();
  System.out.println(numberFormat.parse("12abc"));
  System.out.println(numberFormat.parse("abc12"));
} catch (final ParseException e) {
  System.out.println("parse exception");
}
Run Code Online (Sandbox Code Playgroud)

结果:

12
parse exception
Run Code Online (Sandbox Code Playgroud)

我实际上期望两者都有一个解析异常.如何判断DecimalFormat不允许输入"12abc"

aio*_*obe 17

来自以下文件NumberFormat.parse:

从给定字符串的开头解析文本以生成数字.该方法可能不使用给定字符串的整个文本.

这是一个示例,可以让您了解如何确保考虑整个字符串.

import java.text.*;

public class Test {
    public static void main(String[] args) {
        System.out.println(parseCompleteString("12"));
        System.out.println(parseCompleteString("12abc"));
        System.out.println(parseCompleteString("abc12"));
    }

    public static Number parseCompleteString(String input) {
        ParsePosition pp = new ParsePosition(0);
        NumberFormat numberFormat = new DecimalFormat();
        Number result = numberFormat.parse(input, pp);
        return pp.getIndex() == input.length() ? result : null;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

12
null
null
Run Code Online (Sandbox Code Playgroud)