Why does DecimalFormat allow characters as suffix?

2020-02-10 13:59发布

I'm using DecimalFormat to parse / validate user input. Unfortunately it allows characters as a suffix while parsing.

Example code:

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");
}

Result:

12
parse exception

I would actually expect a parse exception for both of them. How can I tell DecimalFormat to not allow input like "12abc"?

2条回答
放荡不羁爱自由
2楼-- · 2020-02-10 14:36

From the documentation of NumberFormat.parse:

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.

Here is an example that should give you an idea how to make sure the entire string is considered.

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;
    }
}

Output:

12
null
null
查看更多
地球回转人心会变
3楼-- · 2020-02-10 14:51

Use the parse(String, ParsePosition) overload of the method, and check the .getIndex() of the ParsePosition after parsing, to see if it matches the length of the input.

查看更多
登录 后发表回答