Search code examples
javaroundingseparator

Round number in java and add separator


I would like to do this: if I have 1234.5678, I would like 1 234.57. I have tried several things, like:

Object theValue = theValues.get(theHeaderName);
DecimalFormatSymbols theSymbols  = new DecimalFormatSymbols();
theSymbols.setGroupingSeparator(' ');
DecimalFormat theFormatter = new DecimalFormat("#.00", theSymbols);
el.text(theFormatter.format(theValue));

But I don't manage to have the rounding and the separator.


Solution

  • If you overwrite the standard format with #.00 you have no grouping seperator in your format. For your expected case you have to include the grouping seperator again into your custom format:

    DecimalFormat theFormatter = new DecimalFormat("#,###.00", theSymbols);
    

    The pattern definition symbols can be found in the Doc