How to Set Thousands Separator in Java

How to set thousands separator in Java?

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.

How to change the grouping separator (thousands) of DecimalFormat from comma/point to quote using patterns?

Can you use a subclass of DecimalFormat instead?
You could analyze the pattern in the subclass and extract the unusual grouping separator from the pattern. On a call of the subclass's format method, you can use this grouping separator with the original DecimalFormat as shown in your own example code. This is the result that is returned by the format method of the subclass.

Display number in Textview with thousand separator and decimal format

This did the trick:

DecimalFormat decim = new DecimalFormat("#,###.##");
tv.setText(decim.format(someFloat));

How to format a double into thousand separated and 2 decimals using java.util.Formatter

If you need to use the java.util.Formatter, this will work:

double amount = 5896324555.59235328;
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("$ %(,.2f", amount);
System.out.println("Amount is - " + sb);

Expanded on the sample code from the Formatter page.

Showing real numbers with thousands separator while typing

Did you read the docs for DecimalFormat?

....
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
....

Seems like you want to use the format:

new DecimalFormat("#,###.00");


Related Topics



Leave a reply



Submit