Number format (comma separated) according to language

I have a requirement to show a numeric value like 123456789.905 in the following format 123,456,789.90 . But the separation of the comma varies depending on the locale selected on the phone (as if the separation of the comma were selected in the USA, these are 3 places, and if English is selected in India, this is like 12,34,56,789.90 ).

How can I format Double ?

+6
source share
6 answers

So java.text.NumberFormat does not relate to 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 .

+3
source

For the general case, use java.text.NumberFormat :

 NumberFormat nf = NumberFormat.getInstance(); String formatted = nf.format(yourDoubleValue); 

By default, getInstance() returns a NumberFormat that is configured appropriately for the current Locale . You can also change the configuration.

"Separating a comma" is called "grouping."

For a specific case of grouping in the Indian currency format, see: Displaying the currency in the Indian numbering format

+2
source

Try the following:

 try { Locale l = Locale.getDefault(); NumberFormat nf = NumberFormat.getInstance(l); String formato = NumberFormat.getInstance().format(your_data); } catch (Exception e) { e.printStackTrace();} 
0
source

Use NumberFormat , which helps you format and parse numbers for any language.

Your code may be completely independent of the locale conventions for decimal points, thousands separators, or even certain decimal numbers, the numbers used, or the number format is decimal.

 Locale fmtLocale = Locale.getDefault(); NumberFormat formatter = NumberFormat.getInstance(fmtLocale); formatter.format(your_number); 
0
source

Hm, I did not find for any locale in the format NumberFormat.getAvailableLocales() format with two digits between the characters of the grouping (for example, for new Locale("en", "IN") ). Therefore, I think you need to use the DecimalFormat template as follows:

 DecimalFormat df = new DecimalFormat("##,##,##,##,##.###"); System.out.println(df.format(123456789.905)); // Output: 1.23.45.67.89,905 

This is not exactly the same, since DecimalFormat may not have different grouping values, but perhaps this is acceptable to you.

0
source

NumberFormat nf = NumberFormat.getInstance (Locale.getDefault ());

double value = nf.parse (iValue) .doubleValue ();

0
source

All Articles