Java Reference
In-Depth Information
method
print
but allows you to add formatting instructions that specify such things as
the number of digits to include after a decimal point. For example, consider the following:
double
price = 19.8;
System.out.print("$");
System.out.printf("%6.2f", price);
System.out.println(" each");
This code outputs the following line:
$ 19.80 each
The line
System.out.printf("%6.2f", price);
outputs the string
" 19.80"
(one blank followed by
19.80
), which is the value of the
variable
price
written in the format
%6.2f
. In these simple examples, the first argu-
ment to
printf
is a string known as the
format specifier
, and the second argument is
the number or other value to be output in that format. Let's explain this first sample
format specifier.
The format specifier
%6.2f
says to output a floating-point number in a
field
(num-
ber of spaces) of width
6
(room for
six
characters) and to show exactly two digits after
the decimal point. So,
19.8
is expressed as
"19.80"
in a field of width
6
. Because
"19.80"
has only
five
characters, a blank character is added to obtain the
6
-character
string
" 19.80"
. Any extra blank space is added to the front (left-hand end) of the
value output. That explains the
6.2
in the format specifier
%6.2f
. The
f
means the
output is a floating-point number, that is, a number with a decimal point. We will
have more to say about the character
%
shortly, but among other things, it indicates
that a format specification (in this case,
6.2f
) follows.
Before we go on, let's note a few details about the method
printf
. Note that the
first argument is a string that gives a format specifier. Also, note that
printf
, like
print
, does not advance the output to the next line. The method
printf
is like
print
,
not like
println
, in this regard.
The first argument to
printf
can include text as well as a format specifier. For
example, consider the following variant on our example:
format
specifier
field width
double
price = 19.8;
System.out.printf("$%6.2f each", price);
System.out.println();
This code also outputs the following line:
$ 19.80 each
The text before and after the format specifier
%6.2f
is output along with the format-
ted number. The character
%
signals the end of text to output and the start of the