Search code examples
javalocalenumber-formattingstring.format

How can I specify the number of decimal places with NumberFormat in Java?


Let's run this code :

double number = 12345.678888;
String str1 = String.format(Locale.FRANCE, "%.10f", number);
String str2 = NumberFormat.getInstance(Locale.FRANCE).format(number);

System.out.println(str1);
System.out.println(str2);

The outputs will be:

12345,6788880000

12 345,679

But those aren't what I want. I want to specify the number of decimal places with NumberFormat just like String.format() can do. I also tried DecimalFormat as well but I don't think that's the answer.

If I was writing C# code, it could be done simply like this :

string str = string.Format(new CultureInfo("fr-FR"), "{0:#,##0.0000000000}", number);

And the output would be:

12 345,6788880000

How can I achieve the same thing in Java?


Solution

  • Referring to the documentation, NumberFormat has setMaximumFractionDigits and setMinimumFractionDigits, so:

    NumberFormat formatter = NumberFormat.getInstance(Locale.FRANCE);
    formatter.setMaximumFractionDigits(10);
    formatter.setMinimumFractionDigits(10);
    String str2 = formatter.format(number);
    

    That gives me

    12 345,6788880000