Codiqo

Learn Java · lesson 5 of 61 · about 7 minutes

Formatting Output

Print a proper receipt with printf and String.format, and explain your code with comments.

What you'll learn

  • Use printf with %d, %s and %.2f
  • Pad numbers with %02d
  • Write // and /* */ comments

printf

A receipt should say $49.05, not 49 dollars and 5 cents. System.out.printf fills placeholders in a format string:

| Placeholder | For | Example |
|---|---|---|
| %d | whole numbers | 42 |
| %02d | whole numbers, at least 2 digits | 05 |
| %.2f | decimals, 2 places | 3.14 |
| %s | text (or anything) | Ada |
| %n | a new line | |

String.format(...) takes the same placeholders but returns the text instead of printing it.

A receipt line

public class Main {
    public static void main(String[] args) {
        int cents = 4905;
        String show = "Space Pirates";
        System.out.printf("%s: $%d.%02d%n", show, cents / 100, cents % 100);
        System.out.printf("%.2f%n", 12.5);
        String label = String.format("[%5d]", 42);
        System.out.println(label);
    }
}

Output

Space Pirates: $49.05
12.50
[   42]

Comments

Comments are notes for humans: // turns the rest of a line into a comment, and /* ... */ can cover several lines. The compiler ignores both. Use them to say *why* the code does something.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.