Java Reference
In-Depth Information
d-decimal integer
o-octal integer
e-floating-point in scientific notation
There are also special conversions for dates and times (calendar and time classes
are discussed in Chapter 10). The general form of the specifier includes several
optional terms:
%[argument - index$][flags][width][.precision]conversion
The argument - index indicates to which argument the specifier applies. For
example, %2$ indicates the second argument in the list. A flag indicates an
option for the format. For example, “+ requires that a sign be included and
“0 requires padding with zeros. The width indicates the minimum number of
characters and the precision is the number of places for the fraction.
There is also one specifier that doesn't correspond to an argument. It is “%n
and outputs a line break. A \ n can also be used in some cases, but since %n
always outputs the correct platform-specific line separator, it is portable across
platforms whereas \ n is not.
We don't have space here for more than this brief overview of the new format
tools. The Java API Specifications for J2SE 5.0 provides a lengthy description of
the java.util.Formatter class and all of the specifiers and their options.
The following program provides several examples of printf() :
... code segment in PrintfDemo ...
double q = 1.0/3.0;
// Print the number with 3 decimal places.
System.out.printf ("1.0/3.0 = % 5.3f %n", q);
// Increase the number of decimal places
System.out.printf ("1.0/3.0 = %7.5f %n",q);
q = 1.0/2.0;
// Pad with zeros.
System.out.printf ( " 1.0/2.0 = %09.3f %n " , q);
q = 1000.0/3.0;
// Scientific notation
System.out.printf ( " 1000/3.0 = %7.2e %n " , q);
q = 3.0/4567.0;
// More scientific notation
System.out.printf ("3.0/4567.0 = %7.2e %n", q);
 
Search WWH ::




Custom Search