How do I set the default locale?
Author: Deron Eriksson
Description: This Java tutorial describes how to set the default locale.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
The default locale can be set using the Locale.setDefault() method, passing it a Locale object. The SetDefaultLocaleTest class demonstrates this. It displays the default locale and displays a double formatted for the default locale. It creates a new Locale object, specifying Swedish ("sv") and Sweden ("SE"). It sets the default locale to be the Swedish locale. It then once again displays the default locale and the double formatted for the default locale. SetDefaultLocaleTest.javapackage test; import java.text.NumberFormat; import java.util.Locale; public class SetDefaultLocaleTest { public static void main(String[] args) throws Exception { System.out.println("Default locale:" + Locale.getDefault().toString()); formattedDoubleTest(); System.out.println("\nSetting default locale to swedish_sweden"); Locale swedishLocale = new Locale("sv", "SE"); Locale.setDefault(swedishLocale); System.out.println("New default locale:" + Locale.getDefault().toString()); formattedDoubleTest(); } public static void formattedDoubleTest() { double doub = 1234567.89; Locale defaultLocale = Locale.getDefault(); NumberFormat numberFormat = NumberFormat.getInstance(defaultLocale); String formattedNum = numberFormat.format(doub); System.out.println(doub + " formatted (" + defaultLocale.toString() + "):" + formattedNum); } } The execution of SetDefaultLocaleTest on my machine is shown below. Default locale:en_US 1234567.89 formatted (en_US):1,234,567.89 Setting default locale to swedish_sweden New default locale:sv_SE 1234567.89 formatted (sv_SE):1 234 567,89 In the output, we can see that the default locale is English/US ("en_US"). We see that the double is formatted with commas for every three digits to the left of the decimal, and the decimal point is a period. We set the default locale to be Swedish/Sweden ("sv_SE"). After that, we can see that the double is formatted for Sweden, with spaces for every three digits to the left of the decimal, and a comma for the decimal. |