Java Reference
In-Depth Information
When using a locale, a
DecimalFormat
object is obtained by calling
getInstance
in
NumberFormat
and casting the return value, as demonstrated in the following code. Study
the code and see if you can determine its output:
18. NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
19. if(nf instanceof DecimalFormat) {
20. DecimalFormat df = (DecimalFormat) nf;
21. df.applyPattern(“##,#00.00#”);
22. double d1 = 23184.348;
23. double d2 = 3.1;
24. System.out.println(df.format(d1));
25. System.out.println(df.format(d2));
26. }
On line 18 the locale is set to the German language, and
getInstance
typically returns
a
DecimalFormat
object, so line 19 is
true
for most environments. The pattern on line 21
contains both pound signs and zeros and uses English-style commas and a decimal point.
In German, the commas are replaced by a decimal point and vice versa. The output of the
code is
23.184,348
03,10
The double
3.1
is formatted with a leading and trailing zero because the pattern calls
for at least two digits before and after the decimal.
The
NumberFormat.parse
Method
The
NumberFormat
class defi nes a
parse
method for parsing a
String
into a number using
a specifi c locale. The signature of the
parse
method is
public Number parse(String
source) throws ParseException
.
The result of parsing depends on the locale. For example, if the locale is the United
States and the number contains commas, the commas are treated as formatting symbols.
If the locale is a country or language that uses commas as a decimal separator, the comma
is treated as a decimal point. In other words, the value of the resulting number depends on
the locale.
Let's look at an example. The following code parses the same string with different
locales. Study the code and see if you can determine its output:
6. NumberFormat en = NumberFormat.getInstance(Locale.US);
7. NumberFormat fr = NumberFormat.getInstance(Locale.FRANCE);
8.
9. try {
10. String s = “123,45”;
11. System.out.println(en.parse(s));
Search WWH ::
Custom Search