You would like to have some choice over the output format.
printf()
Here is a program that prints Math.PI
using several formats:
import java.lang.Math; public class PrintFloat { public static void main ( String[] args ) { System.out.printf("PI =%8.2f%n", Math.PI); // 8 places, 2 for precision System.out.printf("PI =%8.4f%n", Math.PI); // 8 places, 4 for precision System.out.printf("PI =%8.6f%n", Math.PI); // 8 places, 6 for precision System.out.printf("PI =%f%n", Math.PI); // default } }
This is the result in the USA (other locales will be different):
PI = 3.14 PI = 3.1416 PI =3.141593 PI =3.141593
printf()
looks like this:
printf(formatString, value1, value2, value3, ...)
The format string
describes the desired format.
The characters in the string are printed out as given until
a format specifier is encountered.
This describes how a value is to be
printed.
The first format specifier in the format string matches the first value, the second format specifier matches the second value, and so on. (The program above has one format specifier and one value.) Characters are created from the value according the the specifier.
Often people say that the value is "converted to characters." This is somewhat deceptive since the value itself does not change at all.
A format specifier starts with a %
and is
followed by characters describing the desired format.
The last character matches the data type.
The format specifier %8.4f
matches a floating point value.
The "f" specifies "float".
"8.4" says to use 8 characters total, one for the decimal point,
and 4 for the precision (how many digits follow the decimal point.)
In the above output, the width is 8 characters. This includes the spaces at the beginning. The digits are right justified by default. (This can be changed.)
%n
says to output a newline character.
It is not part of the format specifier for the number.
What do you suspect the following prints: