Here is a method you can use to print a number using the format for several different locales:
public void reformat(double num, String[] locales) {
for (String loc : locales) {
Locale pl = parseLocale(loc);
NumberFormat fmt = NumberFormat.getInstance(pl);
System.out.print(fmt.format(num));
System.out.println("\t" + pl.getDisplayName());
}
}
public static Locale parseLocale(String desc) {
StringTokenizer st = new StringTokenizer(desc, "_");
String lang = "", ctry = "", var = "";
try {
lang = st.nextToken();
ctry = st.nextToken();
var = st.nextToken();
} catch (java.util.NoSuchElementException e) {
; // fine, let the others default
}
return new Locale(lang, ctry, var);
}
The first argument to reformat is the number to format; the other arguments specify locales. We use a
StringTokenizer to break locale argument strings into constituent components. For example, cy_GB
will be broken into the language cy (Welsh), the country GB (United Kingdom), and the empty variant "".
We create a Locale object from each result, get a number formatter for that locale, and then print the
formatted number and the locale. When run with the number 5372.97 and the locale arguments en_US, lv,
it_CH, and lt, reformat prints:
5,372.97 English (United States)
5 372,97 Latvian
5'372.97 Italian (Switzerland)
5.372,97 Lithuanian
A similar method can be written that takes a locale and a number formatted in that locale, uses the parse
method to get a Number object, and prints the resulting value formatted according to a list of other locales:
public void parseAndReformat(String locale, String number,
String[] locales)
throws ParseException
{
Locale loc = LocalNumber.parseLocale(locale);
NumberFormat parser = NumberFormat.getInstance(loc);
Number num = parser.parse(number);
for (String str : locales) {
Locale pl = LocalNumber.parseLocale(str);
NumberFormat fmt = NumberFormat.getInstance(pl);
System.out.println(fmt.format(num));
}
}
When run with the original locale it_CH, the number string "5'372.97" and the locale arguments en_US,
lv, and lt, parseAndReformat prints: