Java Reference
In-Depth Information
Here is an example:
items
int count = 5 ;
double amount = 45.56 ;
System.out.printf( "count is %d and amount is %f", count, amount );
display
count is 5 and amount is 45.560000
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 3.9.
T ABLE 3.9
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.
Output the integer item with width at least 5. If the number of digits in the item is
add spaces before the number. If the number of digits in the item is
6
5,
%5d
7 5,
the width is
automatically increased.
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 add spaces before the
number. If the number of digits before the decimal point in the item is
%10.2f
6
7,
7 7,
the width is
automatically increased.
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.
%10.2e
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.
%12s
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#%3.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 3 , but it needs width 5 to display 51.67, so the width is auto-
matically increased to 5 .
 
Search WWH ::




Custom Search