687
Appendix E
Decimal Format Type*
To give more precise control over the formatting of numbers, Java provides a class called
DecimalFormatthat is part of a package called java.text. The DecimalFormatclass allows us to
create patterns that can be used to format numbers for output. These patterns are in the form
of strings, made up of characters that represent the parts of a formatted number. For example,
the pattern
"###,###"
indicates that a number should be formatted with up to six decimal digits, and when there
are more than three digits in the number, a comma should be used to separate the thousands
from the rest of the number.
There are four steps we must follow to use DecimalFormatpatterns to format numbers:
importjava.text.*;
Declare a variable of typeDecimalFormatfor each number format we wish to use.
For each variable, instantiate a DecimalFormatobject that contains the pattern.
Format each number using the formatmethod associated with each of the
DecimalFormatclass.
Let’s examine each of these steps in turn. You are familiar with writing importdeclarations,
so all you need to do for the first step is remember to put the declaration at the start of your
program. Declaring variables of type DecimalFormatis done in the same way as declaring
variables of type Stringor JFrame. For example:
DecimalFormat dollar; // Format for dollar amounts
DecimalFormat percent; // Format for percentages
DecimalFormat accounting; // Format for negative values in ()
The third step involves using newand the DecimalFormatconstructor to create an object whose
address we can assign to the variable. The call to the constructor contains the string repre-
senting the pattern. Here are statements that associate patterns with each of the variables
declared previously. Don’t be concerned yet with trying to interpret the specific patterns
shown; we explain them shortly.
dollar = newDecimalFormat("$###,##0.00");
percent = newDecimalFormat("##0.00%");
accounting = newDecimalFormat("$###,##0.00;($###,##0.00)");
*This appendix repeats and expands upon the discussion in Chapter 12.