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.
You can use format function with ",";
int no = 124750;
String str = String.format("%,d", no);
//str = 124,750
"," includes locale-specific grouping characters.
docs
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.
BigDecimal bd = new BigDecimal(300000);
NumberFormat formatter = NumberFormat.getInstance(new Locale("en_US"));
System.out.println(formatter.format(bd.longValue()));
EDIT
To get custom grouping separator such as space, do this:
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
symbols.setGroupingSeparator(' ');
DecimalFormat formatter = new DecimalFormat("###,###.##", symbols);
System.out.println(formatter.format(bd.longValue()));