Java Reference
In-Depth Information
DecimalFormat (String pattern)
Constructor: creates a new DecimalFormat object with the specified pattern.
void applyPattern (String pattern)
Applies the specified pattern to this DecimalFormat object.
String format ( double number)
Returns a string containing the specified number formatted according to the
current pattern.
FIGURE 3.7
Some methods of the DecimalFormat class
format method to format a particular value. At a later point, if we want to change
the pattern that the formatter object uses, we can invoke the applyPattern
method. Figure 3.7 describes these methods.
The pattern defined by the string that is passed to the DecimalFormat con-
structor can get fairly elaborate. Various symbols are used to represent particular
formatting guidelines. The pattern defined by the string "0.###" , for example,
indicates that at least one digit should be printed to the left of the decimal point
and should be a zero if the integer portion of the value is zero. It also indicates
that the fractional portion of the value should be rounded to three digits.
This pattern is used in the CircleStats program, shown in Listing 3.5, which
reads the radius of a circle from the user and computes its area and circumference.
Trailing zeros, such as in the circle's area of 78.540, are not printed.
The printf Method
In addition to print and println , the System class has another output method
called printf , which allows the user to print a formatted string containing
data values. The first parameter to the method represents the format string,
and the remaining parameters specify the values that are inserted into the
format string.
For example, the following line of code prints an ID number and a name:
System.out.printf ("ID: %5d\tName: %s", id, name);
The first parameter specifies the format of the output and includes literal
characters that label the output values as well as escape characters such as \t .
The pattern %5d indicates that the corresponding numeric value ( id ) should be
printed in a field of five characters. The pattern %s matches the string parameter
 
Search WWH ::




Custom Search