go to previous page   go to home page   go to next page highlighting

Answer:

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
  }
}

%8.4f

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.


QUESTION 2:

What do you suspect the following prints:

System.out.printf("PI =%5.2f%n", Math.PI);
System.out.printf("PI =%5.3f%n", Math.PI);
System.out.printf("PI =%10.1f%n", Math.PI);

go to previous page   go to home page   go to next page