Precision for floating-point numbers
What you'll learn: How to control exactly how many digits appear after the decimal point when printing floats and doubles.
By default, when you use the %f placeholder in C, the printf() function displays six digits after the decimal point. While this is precise, it often leads to "messy" output, like showing a bank balance as $10.500000 instead of a clean $10.50.
The Dot Notation
To control the precision, you place a dot (.) followed by a number between the percent sign and the f. Think of the dot as the decimal point itself; the number that follows it tells C, "Only show this many seats behind the decimal."
For example:
%.2fmeans "show 2 decimal places."%.0fmeans "show no decimal places" (rounding to the nearest whole number).%.10fmeans "show 10 decimal places."
Automatic Rounding
The best part about using precision specifiers is that C handles the rounding for you. It doesn't just "cut off" the extra numbers; it looks at the next digit to decide whether to round up or down. If you have the number 3.14159 and use %.2f, C sees the 1 in the third decimal place and rounds down, giving you 3.14. If you use %.4f, it sees the 9 and rounds the previous digit up, giving you 3.1416.
Code Example
See how these different specifiers change the output of the same variable:
#include <stdio.h>
int main() {
double pi = 3.1415926535;
float price = 19.95;
float discount = 0.7; // 70 cents
printf("Default pi: %f\n", pi); // 3.141593 (rounds the 6th digit)
printf("Short pi: %.2f\n", pi); // 3.14
printf("Long pi: %.8f\n", pi); // 3.14159265
printf("Money: $%.2f\n", price); // $19.95
printf("Change: $%.2f\n", discount); // $0.70
return 0;
}
Practical Tip
Using %.2f is the industry standard for financial applications or any scenario involving currency. It ensures that even if a calculation results in a long string of decimals (like ), the user only sees the two cents they expect.
Key takeaway
Use %.Nf (where N is a number) to round and limit floating-point output to a specific number of decimal places.