Java Reference
In-Depth Information
double tax = total * TAX_RATE / 100; //
tax is 0.2975
System.out.println("Total: " + total);
System.out.println("Tax: " + tax);
The output is
Total: 3.5
Tax: 0.2975
You may prefer the numbers to be printed with two digits after the decimal point,
like this:
Total: 3.50
Tax: 0.30
You can achieve this with the
printf
method of the
PrintStream
class.
(Recall that
System.out
is an instance of
PrintStream
.) The first parameter
of the
printf
method is a format string that shows how the output should be
formatted. The format string contains characters that are simply printed, and
format specifiers: codes that start with a % character and end with a letter that
indicates the format type. There are quite a few formatsČ
Table 3
shows the most
important ones. The remaining parameters of
printf
are the values to be
formatted. For example,
System.out.printf("Total:%5.2f", total);
prints the string
Total:
, followed by a floating-point number with a width of 5
and a precision of 2. The width is the total number of characters to be printed: in
our case, a space, the digit 3, a period, and two digits. If you increase the width,
more spaces are added. The precision is the number of digits after the decimal
point.
This simple use of printf is sufficient for most formatting needs. Once in a while,
you may see a more complex example, such as this one:
System.out.printf("%-6s%5.2f%n", "Tax:", total);
Here, we have three format specifiers. The first one is
%-6s
. The s indicates a
string. The hyphen is a flag, modifying the format. (See
Table 4
for the most
common format flags. The flags imm
ediately follow the % character.) The hyphen
indicates left alignment. If the string
to be formatted is shorter than the width, it is
167
168