688
The last step is to format the number using a method called format, which is a value-returning
method associated with each of the DecimalFormatobjects. The formatmethod takes as its pa-
rameter a numerical value and returns a value of type Stringthat contains the formatted
number. For example, if we write
out.add(newJLabel(dollar.format(2893.67)));
then a label is added to the content pane called out, which contains a string of the form
$2,893.67
Now that we have seen the process for using patterns to format numeric values, let’s look
at how to write the patterns themselves. The following table shows the characters that can
appear in a pattern string and their meanings.
Now we can interpret the patterns we associate with the DecimalFormatvariables. The
pattern we gave to dollaris "$###,##0.00", which means the number should have a decimal
point with at least two fractional digits and one digit in the integer part. When the integer part
has more than three digits, use a comma as a separator. The number should start with a dol-
lar sign to the left of the first digit.
Character Meaning
0 Display one digit here. If no digit is present in this place, display a zero.
# Display one digit here. If no digit is present in this place, display nothing
here (not even a blank).
, If there are digits on both sides of this place, insert a comma to separate
them. The comma is only meaningful in the integer part of the pattern (the
part to the left of the decimal point).
. Put the decimal point here. If the pattern doesn’t have any digit symbols
( 0 or #) to the right of the period, and the number doesn’t have a fractional
part, don’t insert the decimal point.
% When used anywhere to the right of the rightmost digit in the pattern, this
indicates that the number is a percentage. Multiply it by 100 before display-
ing it, and put the %sign here.
; The pattern to the left of ;is for nonnegative numbers. The pattern to the
right is for negative numbers.
' The character following is one of the special pattern characters, but should
be printed literally (For example, use '#to show a #in the formatted
number.)
other Anything else is inserted exactly as it appears.