View RSS Feed

My Java Tips

java.util.Locale

Rate this Entry
by , 10-30-2011 at 06:27 PM (835 Views)
Locale object deals with the geographical details. Different parts of the world have different languages, currencies and time zones. There are some operations that are different for different geographical areas. These are referred as locale-sensitive operations. These operations uses Locale to tailor the information according to the needs.


Representing numbers is a locale-sensitive operation as formatting of number is different in different parts of the world. The example below prints all the locales available:

Java Code:
Locale[] locales = Locale.getAvailableLocales();
for(int i = 0; i < locales.length; i++){
String language = locales[i].getLanguage();
String country = locales[i].getCountry();
String locale_name = locales[i].getDisplayName();
System.out.println(i + ": " + language + ", " + country + ", " + locale_name);
}
Output:

0: es, PE, Spanisch (Peru)
1: en, , Englisch
2: es, PA, Spanisch (Panama)
3: sr, BA, Serbisch (Bosnien und Herzegowina)
4: mk, , Mazedonisch
5: es, GT, Spanisch (Guatemala)
6: no, NO, Norwegisch (Norwegen)
7: sq, AL, Albanisch (Albanien)
8: bg, , Bulgarisch
...
113: sv, SE, Schwedisch (Schweden)
114: da, DK, Dänisch (Dänemark)
115: es, HN, Spanisch (Honduras)

Locale for a country is set using the constructor as shown in the following example:

Java Code:
Locale deLocale = new Locale("de", "DE");
System.out.println("Language: " +
deLocale.getDisplayLanguage());
System.out.println("Country: " +
deLocale.getDisplayCountry());
Output:

Language: Deutsch
Country: Deutschland

Now lets take an interesting example. Number formatting varies in different parts of the world. In German language, comma is a decimal point and a decimal point is a comma. Its tricky playing with German numbers but thankfully, Locale is there to help us:
Java Code:
Locale deLocale = new Locale("de");
Locale enLocale = new Locale("en");

NumberFormat nf_en = NumberFormat.getInstance(enLocale);
System.out.println("Formatted text (en): " + nf_en.format(734547.3343));

NumberFormat nf_de = NumberFormat.getInstance(deLocale);
System.out.println("Formatted text (de): " + nf_de.format(734547.3343));
Hope this helps.

Submit "java.util.Locale" to Facebook Submit "java.util.Locale" to Digg Submit "java.util.Locale" to del.icio.us Submit "java.util.Locale" to StumbleUpon Submit "java.util.Locale" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments