views:

102

answers:

1

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));
  • 10,50 => 1050
  • 10,5 => 105
  • 0,25 => 25

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:

  • 10,50 => ParseException
  • 10,5 => ParseException
  • 0,25 => ParseException

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

+1  A: 

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.

jarnbjo