Formatted output with printf
20 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
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
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); }}Total: Rs. 136.5 Total: Rs. 136.50 3 x Notebook = Rs. 136.50
What this code does
printlnprints thedoubleas it is:136.5.%.2falways shows two decimals:136.50.- The last line has three placeholders, filled in order by
qty,itemandtotal. - Unlike
println,printfdoes not end the line by itself; the%nat 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.
%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
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); }}85.45454545454545 Attendance: 85.45% Attendance: 85%
What this code does
100.0makes the division a decimal one, as in Arithmetic operators (opens in a new tab).%.2frounds to 2 places and%.0fto 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.
Example 3 · A marks table with widths
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); }}Name Marks Asha 92 Ravindra 85 Kiran 100 Average 92.3
What this code does
%-8sgives every name 8 characters, spaces after it, so the names line up on the left.%6dgives every mark 6 characters, spaces in front, so92and100line up on the right.%6.1fmixes both ideas: width 6 and one decimal, so92.333…prints as92.3.
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
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()); }}Kiran got CGPA 8.5 Characters: 18
What this code does
String.formatbuilds the textKiran got CGPA 8.5but prints nothing.lineis a normal String, so you can print it or ask itslength().
Next step
Check your understanding
10 quick questions