Programming and Problem Solving with Java

(やまだぃちぅ) #1
689

We use the pattern "##0.00%"to tell formatthat the number is a percentage that should
first be multiplied by 100. After that, it is formatted with fractional digits and at least two digits
in the integer part. The percent sign is to be placed to the right of the last digit.
The third pattern,"$###,##0.00;($###,##0.00)", is the most complex of the three, but is
really just a minor variation on the dollarformat. The semicolon indicates that the pattern
on the left, which is the same as the pattern we gave to dollar, is to be used when the num-
ber is nonnegative. The pattern on the right (the same pattern but in parentheses) is to be
used when the number is negative.
Here is a code segment that shows the definition and use of these patterns. Note that we
are also usingJLabel.RIGHTto align the numbers to the right within their labels.


dollar = newDecimalFormat("$###,##0.00");
percent = newDecimalFormat("##0.00%");
accounting = newDecimalFormat("$###,##0.00;($###,##0.00)");


out.add(newJLabel(dollar.format(2893.67), JLabel.RIGHT));
out.add(newJLabel(dollar.format(–2893.67), JLabel.RIGHT));
out.add(newJLabel(dollar.format(4312893.6), JLabel.RIGHT));
out.add(newJLabel(dollar.format( 0 ), JLabel.RIGHT));
out.add(newJLabel(percent.format(0.23679), JLabel.RIGHT));
out.add(newJLabel(percent.format( 1 ), JLabel.RIGHT));
out.add(newJLabel(accounting.format(2893.67), JLabel.RIGHT));
out.add(newJLabel(accounting.format(–2893.67), JLabel.RIGHT));


Let’s take a closer look at each of the labels in this frame. The first label demonstrates
what happens when a positive floating-point value is formatted with the dollar format. Only
as many digits are used as are necessary, and the dollar sign is immediately adjacent to the

Free download pdf