Skip to content
Lesson 5 of 15

Step 1 of 5 · Reading · ~3 min

Learn

Strings

Formatting

Joining pieces with + works for a sentence, but it gives you no control over decimal places, padding or alignment. By the end of this lesson you can print numbers with a fixed number of decimals and lay out aligned columns using Java's format specifiers.

printf and String.format

Two near-twins share one mini-language:

System.out.printf("%s scored %d points%n", "Ana", 42);      // prints it
String line = String.format("%s scored %d points", "Ana", 42);  // returns it

printf writes to standard output; String.format hands you the result as a String to store or pass around. The first argument is the format string; each %... inside it is a placeholder filled by the next argument, in order.

The specifiers

SpecifierMeaningExample result
%sany value as textana
%dinteger42
%fdecimal, 6 places by default2.500000
%.2fdecimal, exactly 2 places3.14
%nline break
%%a literal percent sign%

Between % and the letter you can add a width (minimum number of columns), a precision (digits after the point for %f), and flags:

SpecEffect
%5dright-aligned in 5 columns: 42
%-8sleft-aligned in 8 columns: ana
%07.2f7 columns wide, zero-padded: 0003.14
%05dzero-padded integer: 00042
%,dthousands separators: 1,234,567

Width and precision compose. A leaderboard row:

System.out.printf("%-8s|%5d|%7.1f%n", "ana", 42, 3.14159);
ana     |   42|    3.1

%-8s pads the name to 8 columns on the right, %5d pads the integer on the left, and %7.1f rounds to one decimal and pads to 7 columns. A value longer than its width is not cut: the column simply grows, so a wide column can push everything after it out of line.

Rounding

%.2f rounds, it does not truncate, and ties round up: String.format("%.1f", 0.25) gives 0.3. The value being printed is not changed; only the text is. If you need the rounded number for further math, round it deliberately first.

The traps

The format string is just text, so type mistakes fail at runtime, not at compile time:

System.out.printf("%d%n", 2.5);   // IllegalFormatConversionException: d != java.lang.Double
System.out.printf("%d %d%n", 1);  // MissingFormatArgumentException

%d takes integers only and %f takes decimals only. Count your placeholders against your arguments.

printf adds no newline. Unlike println, it prints exactly what the format string says. Without %n, the next output continues on the same line:

System.out.printf("ready");     // line is never ended
System.out.printf("ready%n");   // complete line

A bare % is a placeholder. To print a percent sign write %%.

Where the starter's numbers come from

Typed input arrives as text. In this lesson's starter, Integer.parseInt(...) and Double.parseDouble(...) turn a text such as "3" or "2.50" into the number it spells, so you can multiply with it. Treat those two lines as given; a later lesson explains them.

Which to use when

One value, nothing fancy: println with +. Decimals, columns or several values in a pattern: printf. Need the text for later: String.format.

Common mistakes

  • Dropping %n and fusing lines together.
  • Using %d for a double (or %f for an int).
  • Expecting %.2f to chop digits off instead of rounding.
  • Putting a width on the last column with a left-align flag, which leaves invisible trailing spaces that an exact-match grader counts.

Your exercise

Print one receipt line for a purchased item, laid out in fixed-width columns: item name, quantity, and the line total with two decimals. The total is the quantity times the unit price, computed before it is formatted. Matching the column widths exactly is the whole task.

Up nextConditionalsControl Flow

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…