Course contentsShow
← Java
Lesson 2228 of 2,87043. String Handling in DepthFree lesson

Formatting Numbers with Precision

Controlling decimal places, padding, and alignment for numeric values using format specifiers.

Formatting Numbers with Precision

You'll learn how to control exactly how numbers appear in strings—from decimal places to padding and alignment.

The Core Idea

When displaying numbers, default toString() often falls short. You might need exactly two decimal places for currency, right-aligned columns of data, or zero-padded IDs. Java's format specifiers give you surgical control over numeric output through String::format, String::formatted, and printf.

The basic pattern is %[flags][width][.precision]conversion:

  • Conversion: d (integer), f (floating-point), e (scientific notation)
  • Precision: .2 means two decimal places for floats
  • Width: minimum character space (padding added if needed)
  • Flags: - (left-align), 0 (zero-pad), + (show sign), , (locale grouping)

Examples in Action

double pi = 3.14159265;

// Two decimal places
"Value: %.2f".formatted(pi);  // "Value: 3.14"

// Right-aligned in 10 spaces (default)
"Price: %10.2f".formatted(42.5);  // "Price:      42.50"

// Left-aligned with minus flag
"Price: %-10.2f".formatted(42.5);  // "Price: 42.50     "

// Zero-padded integers
"ID: %05d".formatted(42);  // "ID: 00042"

// Thousands separator with comma flag
"Population: %,d".formatted(1234567);  // "Population: 1,234,567"

// Always show sign
"Change: %+.1f%%".formatted(2.3);  // "Change: +2.3%"

Alignment Matters

Think of width as reserving table columns: %10.2f reserves 10 characters total, with 2 after the decimal. Numbers align right by default (perfect for columns of data); use - to flip them left.

Key Takeaway: Format specifiers give you pixel-perfect control over numeric display—use .precision for decimals, width for alignment, and flags like 0, -, and , for padding and readability.