Step 4 of 6
Decimals with double
An int can only hold whole numbers. If you need a fraction, like an accuracy of 0.625 or a price of 19.99, use the type double (short for "double-precision floating point"). Print a double with %f.
#include <stdio.h>
int main(void) {
double accuracy = 0.625;
double price = 19.5;
printf("%f\n", accuracy);
printf("%.2f\n", accuracy);
printf("%.1f\n", price);
return 0;
}
0.625000
0.62
19.5
Controlling decimals
Plain %f always shows six digits after the decimal point. Put .N between the % and the f to choose how many: %.2f shows two, %.0f shows none. The value is rounded for printing; the variable itself isn't changed. 0.625 is exactly halfway between 0.62 and 0.63, and for exact ties like this printf rounds to the even last digit, so it prints 0.62 (and %.0f prints 2.5 as 2 but 3.5 as 4). Values that aren't exact ties round the way you'd expect.
How exact are doubles?
A double stores about 15 to 16 significant digits, which is plenty for most things, but it stores numbers in binary, so many decimal fractions (like 0.1) are tiny approximations. That's why you should never use double for money in real software: store cents in an integer instead. For scores, ratios and measurements, double is the right choice.
Common mistakes
- Printing a
doublewith%d(or anintwith%f) prints nonsense. The specifier must match the type. - Writing
double x = 7 / 2;still gives 3.0, because7 / 2is worked out with ints first. You'll dig into that in the next module.
Your turn: store 1.25 in a double named rating and print it with exactly two decimals so the output is Rating: 1.25.