Java Reference
In-Depth Information
format string , which can be followed with any number of additional arguments, each
of which is a value to output. The format string should include one format specifier,
such as %6.2f or %s , for each value output, and they should be in the same order as the
values to be output. For example:
format string
double price = 19.8;
String name = "magic apple";
System.out.printf("$%6.2f for each %s.", price, name);
System.out.println();
System.out.println("Wow");
Display 2.1 Format Specifiers for System.out.printf
CONVERSION
CHARACTER
TYPE OF OUTPUT
EXAMPLES
d
Decimal (ordinary) integer
%5d
%d
f
Fixed-point (everyday notation) floating point
%6.2f
%f
e
E-notation floating point
%8.3e
%e
g
General floating point (Java decides whether to use
E-notation or not)
%8.3g
%g
s
String
%12s
%s
c
Character
%2c
%c
This code outputs the following:
$ 19.80 for each magic apple.
Wow
Note that the format string may contain text as well as format specifiers, and this text
is output along with the values of the other arguments to printf .
You can include line breaks in a format string. For example, the two lines
new lines
System.out.printf("$%6.2f for each %s.", price, name);
System.out.println();
can be replaced by the single line below, which uses the escape sequence \n :
System.out.printf("$%6.2f for each %s.\n", price, name);
 
Search WWH ::




Custom Search