Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number Format (Comma Separation) as per locale

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?

like image 824
reiley Avatar asked Jan 02 '14 12:01

reiley


2 Answers

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.

like image 119
Moritz Petersen Avatar answered Oct 04 '22 22:10

Moritz Petersen


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

like image 30
laalto Avatar answered Oct 04 '22 20:10

laalto