Java Reference
In-Depth Information
See if you can determine the output of the following statements:
NumberFormat pf = NumberFormat.getPercentInstance();
double p = 0.47;
System.out.println(pf.format(p));
Because no Locale is specifi ed, the NumberFormat object uses the default locale. Running
the program on a Windows machine in the United States outputs
47%
Notice that the decimal 0.47 is converted to the number 47 followed by the percent sym-
bol, which is the syntax expected in the United States.
Working with Locales
A locale represents a specifi c geographical, political, or cultural region. The java.util
.Locale class represents a locale. To obtain a Locale object, you can either instantiate
a new one by passing a language into one of its constructors, or you can use one of
the many static Locale fi elds in the Locale class. For example, the following statement
creates a new Locale object for the Portuguese language:
Locale por = new Locale(“pt”);
The string ”pt” represents the two-letter code for Portuguese as specifi ed by ISO 639.2.
View a complete list of language codes online at http://www.loc.gov/standards/
iso639-2/ .
The static fi elds of Locale represent locales for commonly used languages and countries.
For example, if you need a formatter for the Japanese language, use the Locale
.JAPANESE object.
To format currency, use a NumberFormat object obtained from the getCurrencyInstance
methods. The following statements format a double as currency in the country locale of
France:
NumberFormat cf = NumberFormat.getCurrencyInstance(Locale.FRANCE);
double c = 59.99321;
FileWriter fw = new FileWriter(“numberformat.txt”);
PrintWriter pw = new PrintWriter(fw);
pw.println(cf.format(c));
pw.flush();
pw.close();
fw.close();
Search WWH ::




Custom Search