Java Reference
In-Depth Information
Format Specifications for
printf
4
SYNTAX
System.out.printf(
Format_String, Output_1,Output_2, …, Output_Last
);
Format_String
is a string including one format specifier for each
Output
argument.
Format_String
is output with each format specifier replaced by its corresponding
Output
argument in the format given by the
Output
argument's format specifier.
Display A4.1
Format Specii ers for
System.out.printf
CONVERSION
CHARACTER
TYPE OF OUTPUT
EXAMPLES
d
Decimal (ordinary) integer.
%5d
%d
f
%6.2f
%f
Fixed-point (everyday notation) floating-point.
e
%8.3e
%e
E-notation floating point.
g
General floating point. (Java decides whether to use
E-notation or not.)
%8.3g
%g
s
String.
%12s
%s
c
%2c
%c
Character.
b
%6b
%b
Boolean. The corresponding
Output
argument is a Boolean
expression. Outputs
true
or
false
.
n
%n
Denotes a line break. This does not correspond to an
Output
argument. It is approximately equivalent to
\n
.
A number of the form
N
.
M
in a format specifier specifies a field width of
N
spaces
with
M
digits after the decimal point. If one number
N
is given only, it specifies a field
width; if there is a decimal point in the output, then the number of digits after the
decimal point is determined by Java.
When the value output does not fill the field width specified, then blanks are added
in front of the value output. The output is then said to be
right justified
. If you add a
hyphen (
-
) after the
%
, then any extra blank space is placed after the value output and
the output is said to be
left justified
. For example,
%8.2f
is right justified and
%-8.2f
is left justified.