Why does DecimalFormat allow characters as suffix?

2020-02-10 13:57发布

问题:

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"?

回答1:

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


回答2:

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.