Java Reference
In-Depth Information
France uses the euro for its currency, and the output in the
numberformat.txt
fi le looks
like this:
59,99
Notice the
double c
was rounded to two decimal places, a comma appears instead of a
decimal point, and the euro symbol appears after the digits. (I had to write the output to a
fi le because my Windows console was not properly displaying the euro symbol.)
The
DecimalFormat
Class
The
NumberFormat
class has a child class named
DecimalFormat
that adds a variety of fea-
tures for formatting fl oating-point numbers, including the ability to specify precision, lead-
ing and trailing zeros, and prefi xes and suffi xes. You can obtain a
DecimalFormat
object in
two ways:
Instantiate a new
DecimalFormat
using one of its constructors, which is useful when
working with the default locale.
When using a specific locale, invoke the static
getInstance
method in
NumberFormat
and cast the return value to a
DecimalFormat
.
A
DecimalFormat
object has a pattern to represent the format of the decimal number.
The pattern consists of symbols, which include pound signs (#) and zeros to denote place-
holders. The pound signs are placeholders that are ignored if the number has fewer digits
than the pattern. The zeros are placeholders that represent leading and trailing zeros if the
number has fewer digits than the pattern.
The pattern is best understood by an example. The following code creates several
DecimalFormat
objects that format a large fl oating-point number. Study the code and see if
you can determine its output:
8. double d = 1234567.437;
9. DecimalFormat one = new DecimalFormat(“###,###,###.###”);
10. System.out.println(one.format(d));
11.
12. DecimalFormat two = new DecimalFormat(“000,000,000.00000”);
13. System.out.println(two.format(d));
14.
15. DecimalFormat three = new DecimalFormat(“$#,###,###.##”);
16. System.out.println(three.format(d));
The
DecimalFormat
object on line 15 demonstrates adding a symbol to the pattern, in
this case a dollar sign. The output of the code is
1,234,567.437
001,234,567.43700
$1,234,567.44
The
DecimalFormat
object on line 12 puts leading and trailing zeros on the number, and
the one from line 15 prefi xes a dollar sign and the decimal value is rounded up.
Search WWH ::
Custom Search