Search code examples
javafloating-pointformatlocale

Why Java double print format differs depending on using String.format or not


This code:

 System.out.println(String.format("%f", Math.PI));
 System.out.println(Math.PI);

produces that result on my computer:

3,141593
3.141592653589793

Why does the first line print float number with comma while the second one uses dot?


Solution

  • String.format(String, Object...) uses the formatting rules from Locale.getDefault(). String.valueOf(double) does not. Use String.format(Locale, String, Object...) to explicitly specify the locale to use.