14

DecimalFormat uses ',' as the default grouping separator character.

What is the correct way to tell DecimalFormat that we don't want any grouping separator character? I currently use symbols.setGroupingSeparator('\0'), and it seems to work, but it looks ugly.

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator('\0');

DecimalFormat df = new DecimalFormat();
df.setDecimalFormatSymbols(symbols);

ParsePosition pp = new ParsePosition(0);
Number result = df.parse("44,000.0", pp);   // this should fail, as I don't want any grouping separatator char.
if (pp.getIndex() != input.length())
   throw new Exception("invalid number: " + input, 0);

What is the correct way to tell DecimalFormat that we don't want any grouping separator char?

1ac0
  • 2,875
  • 3
  • 33
  • 47
David Portabella
  • 12,390
  • 27
  • 101
  • 182

2 Answers2

40

Turn off grouping by calling setGroupingUsed:

df.setGroupingUsed(false);
dogbane
  • 266,786
  • 75
  • 396
  • 414
4

You can use the setGroupingUsed() method, but that won't make the format reject the number, it will just stop parsing at the first separator. Number parsing with formats will ignore everything after the first invalid character.

millimoose
  • 39,073
  • 9
  • 82
  • 134