Java Reference
In-Depth Information
}
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 ar-
guments specify locales. We use a
StringTokenizer
to break locale ar-
gument 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 loc-
ale 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 loc-
ales: