Skip to main content
Engineering LibreTexts

11.6: Formatting Output

  • Page ID
    15226
  • When you output a double using print or println, it displays up to 16 decimal places:

    System.out.print(4.0 / 3.0);
    

    The result is:

    1.3333333333333333
    

    That might be more than you want. System.out provides another method, called printf, that gives you more control of the format. The “f” in printf stands for “formatted”. Here’s an example:

    System.out.printf("Four thirds = %.3f", 4.0 / 3.0);
    

    The first value in the parentheses is a format string that specifies how the output should be displayed. This format string contains ordinary text followed by a format specifier, which is a special sequence that starts with a percent sign. The format specifier \%.3f indicates that the following value should be displayed as floating-point, rounded to three decimal places. The result is:

    Four thirds = 1.333
    

    The format string can contain any number of format specifiers; here’s an example with two:

    int inch = 100;
    double cm = inch * CM_PER_INCH;
    System.out.printf("%d in = %f cm\n", inch, cm);
    

    The result is:

    100 in = 254.000000 cm
    

    Like print, printf does not append a newline. So format strings often end with a newline character.

    The format specifier \%d displays integer values (“d” stands for “decimal”). The values are matched up with the format specifiers in order, so inch is displayed using \%d, and cm is displayed using \%f.

    Learning about format strings is like learning a sub-language within Java. There are many options, and the details can be overwhelming. Table 3.1 lists a few common uses, to give you an idea of how things work. For more details, refer to the documentation of java.util.Formatter. The easiest way to find documentation for Java classes is to do a web search for “Java” and the name of the class.

    Table 3.1: Example format specifiers
    \%d decimal integer 12345
    \%08d padded with zeros, at least 8 digits wide 00012345
    \%f floating-point 6.789000
    \%.2f rounded to 2 decimal places 6.79
    • Was this article helpful?