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

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

Posted by: admin October 21, 2018 Leave a comment

Questions:

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?

Answers: