Why Java double print format is different based on String.format use or not

This code:

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

      

produces this result on my computer:

3,141593
3.141592653589793

      

Why does the first line print a semicolon number while the second uses a period?

+2


a source to share


4 answers


String.format(String, Object...)

uses formatting rules from Locale.getDefault()

. String.valueOf(double)

no. Use String.format(Locale, String, Object...)

to explicitly specify the language to use.



+4


a source


The former respect your language setting (which appears to use a comma for the thousands separator).



+2


a source


The first uses the default locale .

second is probably using a standard (non-localizable) implementation.

0


a source


String.format () uses the locale of your system. There should also be a variant of this method, you can pass a specific instance of Locale. When using println () on the other hand, the toString () method is called - in your case Double # toString (), which is more often than not a fairly basic implementation, good enough to represent a clear display of the object.

0


a source







All Articles