6

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?

joragupra
  • 692
  • 1
  • 12
  • 23
reiley
  • 3,759
  • 12
  • 58
  • 114

6 Answers6

3

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.

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
2

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

Community
  • 1
  • 1
laalto
  • 150,114
  • 66
  • 286
  • 303
0

Try this one:

try {
                    Locale l = Locale.getDefault();
                    NumberFormat nf = NumberFormat.getInstance(l);
                    String formato = NumberFormat.getInstance().format(your_data);

                } catch (Exception e) {
                    e.printStackTrace();}
VINIL SATRASALA
  • 614
  • 5
  • 11
0

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

Your code can be completely independent of the locale conventions for decimal points, thousands-separators, or even the particular decimal digits used, or whether the number format is even decimal.

Locale fmtLocale = Locale.getDefault();
NumberFormat formatter = NumberFormat.getInstance(fmtLocale);
formatter.format(your_number);
user987339
  • 10,519
  • 8
  • 40
  • 45
0

Hm, I have not found for any locale in NumberFormat.getAvailableLocales() a format with only two digits between grouping signs (for example for new Locale("en", "IN")). So I think you have to use DecimalFormat-pattern like this:

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

It is not exactly the same since DecimalFormat is not able to have varying counts of grouping sizes, but maybe this is acceptable for you.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
0

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

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

Munesh
  • 1,509
  • 3
  • 20
  • 46