Java Reference
In-Depth Information
Items must match the format specifiers in order, in number, and in exact type. For example,
the format specifier for count is %d and for amount is %f . By default, a floating-point value
is displayed with six digits after the decimal point. You can specify the width and precision in
a format specifier, as shown in the examples in Table 4.12.
T ABLE 4.12
Examples of Specifying Width and Precision
Example
Output
Output the character and add four spaces before the character item, because the
width is 5.
%5c
%6b
Output the Boolean value and add one space before the false value and two spaces
before the true value.
%5d
Output the integer item with width at least 5. If the number of digits in the item is
6
5, add spaces before the number. If the number of digits in the item is 7
5, the
width is automatically increased.
%10.2f
Output the floating-point item with width at least 10 including a decimal point
and two digits after the point. Thus, there are 7 digits allocated before the decimal
point. If the number of digits before the decimal point in the item is
7, add spaces
before the number. If the number of digits before the decimal point in the item is
7
6
7, the width is automatically increased.
%10.2e
Output the floating-point item with width at least 10 including a decimal point, two
digits after the point and the exponent part. If the displayed number in scientific
notation has width less than 10, add spaces before the number.
%12s
Output the string with width at least 12 characters. If the string item has fewer
than 12 characters, add spaces before the string. If the string item has more than
12 characters, the width is automatically increased.
If an item requires more spaces than the specified width, the width is automatically
increased. For example, the following code
System.out.printf( "%3d#%2s#%4.2f\n" , 1234 , "Java", 51.6653 );
displays
1234#Java#51.67
The specified width for int item 1234 is 3 , which is smaller than its actual size 4 . The
width is automatically increased to 4 . The specified width for string item Java is 2 , which is
smaller than its actual size 4 . The width is automatically increased to 4 . The specified width
for double item 51.6653 is 4 , but it needs width 5 to display 51.67, so the width is automati-
cally increased to 5 .
By default, the output is right justified. You can put the minus sign ( - ) in the format
specifier to specify that the item is left justified in the output within the specified field. For
example, the following statements
right justify
left justify
System.out.printf( "%8d%8s%8.1f\n" , 1234 , "Java", 5.63 );
System.out.printf( "%-8d%-8s%-8.1f \n" , 1234 , "Java", 5.63 );
display
8
1234
8
8
Java
5.6
1234
Java
5.6
where the square box (
n
) denotes a blank space.
 
 
Search WWH ::




Custom Search