Ad space (banner)
Java Lessons
Lesson 49 / 68

Formatting Numbers (Padding Digits, Decimal Places)

This lesson covers formatting numbers in Java — padding digits and decimal places — so you can display numbers in a readable format. It's for anyone searching "Java printf format usage."

System.out.printf("%.2f", value) aligns the number of decimal places, and System.out.printf("%03d", value) zero-pads a number to a fixed width. Handy for displaying a monetary amount, or building a sequentially-numbered filename.

The example uses System.out.printf("%.2f dollars%n", price) to format 1234.5 as "1234.50 dollars," with two decimal places, and System.out.printf("%03d%n", num) to zero-pad 7 into "007," a 3-digit format. %n represents a platform-independent line break.

A common early mistake is the sheer number of format specifiers available. There's %f (floating point), %d (integer), %s (string), and more — you need to choose the one that matches your purpose.

In real projects, a raw calculation result often has inconsistent digit counts and looks messy, so applying formatting like this right before display is standard practice.

📖 Reference code
✍️ Your code
Type your code, then press "Run"

🧪 This site can't compile or run Java directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser — nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)