Formatting decimals with %.nf
What you'll learn: How to control exactly how many digits appear after the decimal point when printing numbers.
The messy decimal problem
By default, when you use the %f placeholder to print a float or a double in C, the computer is quite generous—it typically displays six digits after the decimal point. If you are calculating the price of a cup of coffee, your output might look like $3.500000.
While mathematically correct, it looks cluttered and unprofessional. In the real world, we often need to "round" our display to fit the context, such as two decimal places for currency or zero for a whole percentage.
Using the magic dot
To fix this, we insert a "precision specifier" between the % and the f. The syntax is %.nf, where n is the number of decimal places you want to show.
Think of the dot as a boundary marker. Everything to the right of the dot tells C: "Stop showing digits after this many spots."
%.1fshows one decimal place (e.g.,3.5)%.2fshows two decimal places (e.g.,3.50)%.0fhides the decimal entirely, rounding to the nearest whole number.
See it in action
In the example below, notice how C doesn't just cut the numbers off; it rounds them appropriately for the display.
#include <stdio.h>
int main() {
double pi = 3.14159265;
double price = 19.99;
// Default printing (usually 6 places)
printf("Default: %f\n", pi);
// Rounded to two places for money
printf("Price: $%.2f\n", price);
// Rounded to three places
printf("Pi to three places: %.3f\n", pi);
// Rounded to the nearest whole number
printf("Whole number pi: %.0f\n", pi);
return 0;
}
How rounding works
It is important to remember that %.nf only changes how the number looks on the screen. It does not change the actual value stored in your variable. If you print 3.148 using %.2f, the screen will show 3.15, but the variable inside the computer's memory still holds the precise 3.148 for future calculations.
Key takeaway
Use %.nf to round your output to n decimal places for cleaner, more readable results.