Marcel
Marcel

Reputation: 3825

Javas DecimalFormat: how to reject "invalid" input with grouped decimals?

When using the following NumberFormat:

    NumberFormat amountFormat = NumberFormat
        .getNumberInstance(I18N.getThreadLocale());
    amountFormat.setMaximumFractionDigits(2);
    amountFormat.setMinimumFractionDigits(2);

I get the following results when parsing via

    System.out.println(amountFormat.parse(value));

I know that in Locale.ENGLISH the "," is the group separator. But I don't think that the above results make sense. And our customers get weird about this formatting.

How can I disable this grouping?

I would like to have the following results:

Is there a standard way to do this? Or do I have to program my own NumberFormat?

Upvotes: 1

Views: 1003

Answers (1)

jarnbjo
jarnbjo

Reputation: 34313

One problem is the grouping character (',' in an English locale). To disable grouping support for the NumberFormat instance, you can simply invoke setGroupingUsed(false).

This however, leads to a different problem, namely that NumberFormat parses from the beginning of the string, until it reaches an unknown character. parse("12foo") will return 12, just as parse("10,50") will return 10 if grouping is disabled. To check if the entire input string was actually parsed, you have to use the parse methods with a ParsePosition argument and check its index and if the input string was parsed to the end or if the parser stopped at an earlier position in the string.

Upvotes: 3

Related Questions