I'm trying to format a string to add commas between 3 digit groups
EG:
1200.20 >> 1,200.20
15000 >> 15,000
I'm trying to figure out how to do it with DecimalFormat, to this point I have been using a script of my own that seems overly complicated. I cannot figure out how to do it, using # simply hides trailing zeroes and using 0 adds them to the number.
This is what I'm trying right now:
DecimalFormat df = new DecimalFormat("###,###.####", new DecimalFormatSymbols(Locale.US));
resultStr = df.format(Double.valueOf(resultStr));
I'm sure it must be easy but I'm not sure how to do it. I don't have to do it with DecimalFormat, I just thought it would be the easier way. How can I simply add the commas without modifying the decimals in any way?
You should use a NumberFormat object and set it to use grouping. Something like
which returns:
An advantage of this is that the solution can be locale specific.
Edited
Now shows an example with a DecimalFormat object. Note that you should set the grouping size if you use this.
You can also try something like
Why don't you use the comma
,
flag withprintf
.The output will be
And the good news: The actual generated separator used
is specific to the user’s locale
You should be able to do exactly what you want:
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
I couldn't make any of the other solutions work, some round the decimals, some add trailing zeroes or some remove trailing zeroes.
I don't plan of accepting my own answer but I'll post my script in case somebody finds it useful.