This short example shows how floating-point numbers behave in C and why simple expressions like 0.1 + 0.2
don't always behave as you'd expect.
#include <stdio.h>
int main () {
printf("%f\n", 0.1 + 0.2); // Default format: 6 digits after decimal
printf("%.17f\n", 0.1 + 0.2); // Full precision for a double
}
0.300000
0.30000000000000004
C uses the IEEE 754 standard to represent floating-point numbers (float
, double
).
- Some numbers like
0.5
are exact in binary. - But others like
0.1
or0.2
cannot be exactly represented.
So when you write:
0.1 + 0.2
You're actually adding:
0.10000000000000000555... + 0.20000000000000001110...
Which gives:
0.30000000000000004441...
This is not exactly 0.3
, though it's very close.
Format String | Meaning | Output |
---|---|---|
%f |
6 digits (default) | 0.300000 |
%.17f |
17 digits = full double | 0.30000000000000004 |
The value 0.30000000000000004
is rounded to 0.300000
when printed with %f
.
- Floating-point numbers are not exact.
- Even simple decimal values like
0.1
and0.2
can have invisible errors due to binary representation. - C (and most other languages) hides this by default, but you can reveal it using higher precision formats.
- Always be careful when comparing floats or expecting exact decimal values in output.
โ This is expected behavior, not a bug!