Search code examples
javanumber-formattingbigdecimal

How to set thousands separator in Java?


How to set thousands separator in Java?
I have String representation of a BigDecimal that I want to format with a thousands separator and return as String.


Solution

  • This should work (untested, based on JavaDoc):

    DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
    DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
    
    symbols.setGroupingSeparator(' ');
    formatter.setDecimalFormatSymbols(symbols);
    System.out.println(formatter.format(bd.longValue()));
    

    According to the JavaDoc, the cast in the first line should be save for most locales.