I have a requirement to show a number value like 123456789.905
in the following format 123,456,789.90
. But the comma separation changes depending on the locale selected in the phone (as if with US English selected comma separation is 3 places and if India English is selected it is like 12,34,56,789.90
).
How can I format my Double
?
So, java.text.NumberFormat
doesn't slove the problem, unfortunately, but com.ibm.icu.text.NumberFormat
does.
You can use this:
Double d = 123456789.905;
com.ibm.icu.text.NumberFormat format = com.ibm.icu.text.NumberFormat.getNumberInstance(new Locale("en", "in"));
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
System.out.println(format.format(d));
This outputs: 12,34,56,789.90
.
For the generic case, use java.text.NumberFormat
:
NumberFormat nf = NumberFormat.getInstance();
String formatted = nf.format(yourDoubleValue);
By default getInstance()
returns a NumberFormat
that is configured as appropriate for the current Locale
. You can change the configuration yourself, too.
The "comma separation" is called "grouping".
For the specific case of grouping in an Indian currency format, see: Displaying Currency in Indian Numbering Format
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