You can use java. util. text. NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add a comma between them.
The java. text. DecimalFormat class is used for formatting numbers as per customized format and as per locale.
The character used as the thousands separatorIn the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.
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()));
try this code to format as used in Brazil:
DecimalFormat df = new DecimalFormat(
"#,##0.00",
new DecimalFormatSymbols(new Locale("pt", "BR")));
BigDecimal value = new BigDecimal(123456.00);
System.out.println(df.format(value.floatValue()));
// results: "123.456,00"
If you are using thousand separator for Integer data type use 1.
String.format("%,d\n", 58625) and output will be 58,625
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With