views:

314

answers:

4

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?

+1  A: 

The former respects your locale settings (which seems to use comma for thousand separator).

Konrad Garus
+3  A: 

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.

Gunslinger47
A: 

The first one uses the default locale.

The second one probably uses a default (not localizable) implementation.

kgiannakakis
A: 

String.format() uses the locale of your system. There should also be a variant of that method, you can pass a specific Locale instance. When using println() on the other hand, the object's toString() method is invoked - in your case Double#toString(), which is mosten times a rather basic implementation, just good enough to present a understandable display of of the object.

Ridcully