Ad space (banner)
🔧C Lessons
Lesson 49 / 68

Formatting Numbers (Padding Digits, Decimal Places)

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

printf("%.2f", value) aligns the number of decimal places, and 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 printf("%.2f dollars ", price) to format 1234.5 as "1234.50 dollars," with two decimal places, and printf("%03d ", num) to zero-pad 7 into "007," a 3-digit format. Notice the difference between the %f and %d format specifiers.

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 C 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)