0Pricing
Java Academy · Lesson

NumberFormat and printf

Format numbers for display using NumberFormat, DecimalFormat, and printf patterns.

NumberFormat and printf

Java provides rich number formatting APIs: NumberFormat for locale-aware currency/percent, DecimalFormat for custom patterns, and printf/String.format for C-style formatting.

String.format Basics

String.format() uses format specifiers to build strings. Common specifiers: %d (integer), %f (float), %s (string), %n (newline).

String name = "Alice";
int score = 95;
double avg = 87.567;

String msg = String.format(
    "Player: %s | Score: %d | Average: %.2f", name, score, avg);
System.out.println(msg);
// Player: Alice | Score: 95 | Average: 87.57

// printf is equivalent — formats directly to output
System.out.printf("%-10s %5d %8.2f%n", name, score, avg);
// Alice          95    87.57

All lessons in this course

  1. The Math Class Essentials
  2. Integer Arithmetic & Overflow
  3. BigDecimal for Financial Calculations
  4. NumberFormat and printf
← Back to Java Academy