(^604) | Multidimensional Arrays and Numeric Computation
beginning of your code. Declaring variable of class DecimalFormatis done in the same way as
declaring other kinds of object variables. For example:
DecimalFormat dollar; // Format for dollar amounts
DecimalFormat percent; // Format for percentages
The third step involves using newand the DecimalFormatconstructor to create a value we
can assign to the variable. The call to the constructor contains the string representing the pat-
tern. The following statements associate patterns with each of the variables declared above.
In these patterns, the #sign and 0 represent the places that digits should be placed. Other
characters ($, comma, period,%) are to be inserted directly into the formatted number. A 0
indicates a digit that is requred (a 0 is to be inserted if the number doesn’t have a nonzero
digit in that place), and #is for optional digits..
dollar = new DecimalFormat("$###,##0.00");
percent = new DecimalFormat("##0.00%");
The last step is to format the number using a method called format, which is a value-re-
turning method associated with each of the DecimalFormatobjects. The formatmethod takes
as its parameter a numerical value and returns a value of type Stringthat contains the for-
matted number. For example, if we write
out.add(new JLabel(dollar.format(2893.6723));
out.add(new JLabel(percent.format(0.142));
then labels are added to the content pane called out, which contain strings of the form
$2,893.67 and 14.20%
The first string matches the format pattern associated with dollar. Note that the use of the
%sign in the percentpattern causes the value to be multiplied by 100 before it is formatted.
See Appendix E for more information on writing the patterns themselves.
やまだぃちぅ
(やまだぃちぅ)
#1