Skip to lesson

Formatted output with printf

Formatted output means printing values in a fixed, neat shape: a price with exactly two decimals, or marks lined up in columns. Java does this with System.out.printf().

printf and placeholders

A shop bill prints Total: Rs. 136.5, but real bills show two decimals, Rs. 136.50, and println cannot do that.

Syntax
System.out.printf("text with placeholders", value1, value2);

printf prints a text with placeholders in it, each starting with %, and fills them from left to right with the values after the text.

Example 1 · A neat bill with %s, %d and %.2f

Receipt.javaJava
public class Receipt {    public static void main(String[] args) {        String item = "Notebook";        int qty = 3;        double price = 45.5;        double total = qty * price;        System.out.println("Total: Rs. " + total);        System.out.printf("Total: Rs. %.2f%n", total);        System.out.printf("%d x %s = Rs. %.2f%n", qty, item, total);    }}
Output
Total: Rs. 136.5
Total: Rs. 136.50
3 x Notebook = Rs. 136.50

What this code does

  • println prints the double as it is: 136.5. %.2f always shows two decimals: 136.50.
  • The last line has three placeholders, filled in order by qty, item and total.
  • Unlike println, printf does not end the line by itself; the %n at the end of each text does.

Each placeholder is called a format specifier, and its letter says what kind of value goes there: %d a whole number (int or long), %.2f a decimal with 2 digits after the point, %s text, and %n a new line.

The letter must match the value. %d with a double stops the program with IllegalFormatConversionException: d != java.lang.Double.

Decimal places and the % sign

You attended 47 of 55 classes, and println shows 85.45454545454545, which nobody wants to read.

The number after the point sets the decimals: %.2f gives 2 and %.0f gives none, and Java rounds the value. A real percent sign is written %%.

Example 2 · Rounding a percentage

Attendance.javaJava
public class Attendance {    public static void main(String[] args) {        int attended = 47;        int total = 55;        double percent = attended * 100.0 / total;        System.out.println(percent);        System.out.printf("Attendance: %.2f%%%n", percent);        System.out.printf("Attendance: %.0f%%%n", percent);    }}
Output
85.45454545454545
Attendance: 85.45%
Attendance: 85%

What this code does

  • 100.0 makes the division a decimal one, as in Arithmetic operators (opens in a new tab).
  • %.2f rounds to 2 places and %.0f to a whole number.
  • In %.2f%%%n, read it as three parts: %.2f, then %% (the sign), then %n.

Rounding goes up when the next digit is 5 or more: 82.456 with %.2f prints 82.46, and %.1f%% prints a percentage like 85.5%.

Width: lining up columns

A marks table looks ragged when names have different lengths.

A number right after % sets the width, the least number of characters the value takes. With a minus, as in %-8s, the spaces go after the value. The picture shows the parts of %8.2f.

The format specifier %8.2f has four parts: % starts it, 8 is the width, .2 is the number of decimals and f is the type. For 136.5 it prints 136.50 with two spaces in front, 8 characters in all.

Example 3 · A marks table with widths

MarksTable.javaJava
public class MarksTable {    public static void main(String[] args) {        System.out.printf("%-8s%6s%n", "Name", "Marks");        System.out.printf("%-8s%6d%n", "Asha", 92);        System.out.printf("%-8s%6d%n", "Ravindra", 85);        System.out.printf("%-8s%6d%n", "Kiran", 100);        System.out.printf("%-8s%6.1f%n", "Average", (92 + 85 + 100) / 3.0);    }}
Output
Name     Marks
Asha        92
Ravindra    85
Kiran      100
Average   92.3

What this code does

  • %-8s gives every name 8 characters, spaces after it, so the names line up on the left.
  • %6d gives every mark 6 characters, spaces in front, so 92 and 100 line up on the right.
  • %6.1f mixes both ideas: width 6 and one decimal, so 92.333… prints as 92.3.
A value longer than the width is never cut: Java prints all of it and the column just gets pushed. Pick a width a little bigger than your longest value.

String.format: build the text, print it later

Sometimes you want the neat text in a variable instead, to print it twice or count its characters.

String.format() takes the same placeholders as printf but does not print: it gives back the formatted text as a String.

Example 4 · String.format

Result.javaJava
public class Result {    public static void main(String[] args) {        String name = "Kiran";        double cgpa = 8.456;        String line = String.format("%s got CGPA %.1f", name, cgpa);        System.out.println(line);        System.out.println("Characters: " + line.length());    }}
Output
Kiran got CGPA 8.5
Characters: 18

What this code does

  • String.format builds the text Kiran got CGPA 8.5 but prints nothing.
  • line is a normal String, so you can print it or ask its length().

Next step

Check your understanding

10 quick questions