System.out.printf("%4d\t $%,1.0f%n", 2020, 39552784.03);
2020 $39,552,784
This is not the best way to do this, but works, somewhat.
import java.util.Locale; public class LocaleDemo { public static void main ( String[] args ) { int value = 123456789 ; System.out.println( "Default Locale = " + Locale.getDefault() ); System.out.printf( "value = %,12d%n", value ); } }
When the Java virtual machine starts running,
it creates a default locale object.
This object affects the format of strings created by printf()
.
Depending on the default locale, a program creates different strings for the same number.
On my computer (in the US) the above program writes
Default Locale = en_US value = 123,456,789
The number has been formatted correctly for the locale in which the program is running.
The static method Locale.getDefault()
asks the virtual machine
for a reference to its default locale object.
The println()
statement uses that object's
toString()
method to produce: en_US
.
This specifies that the default language is English and the default country is US. Your computer might output a different locale code and may format the number differently.
Recall that a static method can be run without instantiating an object of the class.
So the static method getDefault()
can be run by using Locale.getDefault()
.
In Germany the program prints:
Default Locale = de_DE value = 123.456.789
Locales specify both language and country.
What do you suspect the following fragment writes?
double value = 12345.6789 ; Locale.setDefault( Locale.FRANCE ); System.out.println( "Default Locale = " + Locale.getDefault() ); System.out.printf( "value = %,10.4f%n", value );
The data type is now float and the locale has been changed.