Skip to content
systemcoding.dev
Fundamentals

Why 0.1 + 0.2 Does Not Equal 0.3 in Floating Point

See why 0.1 and 0.2 have no exact binary form, how their stored values add to 0.30000000000000004, and what to do about it in C code with %.17g and hex output.

6 min read
Summarize in AI
Flat illustration of a hex dump with one byte highlighted, with the C, Zig and Rust logos.

Type 0.1 + 0.2 into almost any language and the answer prints as 0.30000000000000004. A test for equality with 0.3 fails. It looks like a bug, and it appears in every language that uses binary floating point, from C to JavaScript to Python. It is not a bug: it is what the numbers are. The decimal fractions 0.1 and 0.2 have no exact binary representation, so the computer stores close neighbours, and the sum of the neighbours is not the neighbour of the sum. This post shows the stored values in hex and in decimal, explains where the extra digits come from, shows that the result depends on the precision, and gives the rules for living with it. The programs use C17 with GCC 14 on x86-64 Linux, where double is IEEE 754 binary64 computed with SSE2.

A fraction that never ends

In decimal, one third is 0.333... with the threes going on forever, because 3 does not divide a power of 10. The same thing happens in binary with a different set of numbers. A fraction has a finite binary expansion only if its denominator, in lowest terms, is a power of 2. A half, a quarter and an eighth are fine. One tenth is 1 over 10, and 10 has a factor of 5, so the binary expansion never ends:

0.1 in binary is 0.0001100110011001100110011..., with the group 0011 repeating forever.

A double keeps 53 significant bits, so the expansion is cut off and rounded. The stored value is the closest double to 0.1, which is slightly more than 0.1. For 0.2, the same pattern shifted by one place, the stored value is slightly more than 0.2, and it is exactly twice the stored 0.1, since doubling only changes the exponent. For 0.3, the nearest double happens to be slightly less than 0.3.

The stored values

The C format %.17g prints 17 significant digits, which is enough to tell any two doubles apart, and %a prints the exact hexadecimal form of the value. Together they show what is really in memory.

sum.cc
#include <stdio.h>

int main(void)
{
    double a = 0.1;
    double b = 0.2;
    double c = a + b;
    double d = 0.3;

    printf("0.1       = %.17g  %a\n", a, a);
    printf("0.2       = %.17g  %a\n", b, b);
    printf("0.1 + 0.2 = %.17g  %a\n", c, c);
    printf("0.3       = %.17g  %a\n", d, d);
    printf("equal: %d\n", c == d);
    return 0;
}

The %a form is the significand in hex and the power of two: 0x1.999999999999ap-4 is 1.999999999999a hex times 2 to the minus 4.

Text
0.1       = 0.10000000000000001  0x1.999999999999ap-4
0.2       = 0.20000000000000001  0x1.999999999999ap-3
0.1 + 0.2 = 0.30000000000000004  0x1.3333333333334p-2
0.3       = 0.29999999999999999  0x1.3333333333333p-2
equal: 0

Read the hex digits. The values 0.1 and 0.2 share the digits 1.999999999999a and differ only in the exponent, which confirms that one is exactly twice the other. The repeating 9 digits in hex are the 1001 pattern from the binary expansion, rounded up at the end to a. The true sum of the two stored numbers is 0x1.3333333333333...8p-2, a value that falls exactly half-way between two adjacent doubles, ...333 and ...334. The rule for ties is to round to the even neighbour, and the even one ends in 4, so the result is 0x1.3333333333334p-2. The double nearest to 0.3 is 0x1.3333333333333p-2. They differ by one unit in the last place, so the two numbers are neighbours, and == reports false.

The decimal digits are the same story in a different notation. The stored 0.1 is 0.1000000000000000055511151231257827..., and the stored 0.2 is 0.200000000000000011102230246251565.... Their sum is about 0.3000000000000000166, which rounds to the double whose decimal value is 0.3000000000000000444089209850062616.... That value is the nearest double to the exact sum, and it is one step above the nearest double to 0.3.

Where the output hides it

The short form printf("%g", 0.1 + 0.2) prints 0.3, because %g uses 6 significant digits by default and the error is in the 17th. The extra digits are always there, and printing hides them. Python's repr and JavaScript's default number to string conversion print the shortest string that reads back as the same double, and for the sum that is 0.30000000000000004, which is why those languages show the difference immediately. The comparison == has no rounding at all, so it always sees the exact stored values.

The answer changes with precision

The result is not a law of nature, it depends on the format. In single precision, the same sum compares equal. The float stored for 0.1 is slightly above 0.1, and the one for 0.2 is exactly twice that, and when they are added, the exact sum rounds to the same float as the nearest to 0.3, which is 0x3E99999A.

single.cc
#include <stdio.h>

int main(void)
{
    float a = 0.1f;
    float b = 0.2f;
    float c = a + b;
    float d = 0.3f;

    printf("%.9g + %.9g = %.9g\n", a, b, c);
    printf("0.3f = %.9g\n", d);
    printf("equal: %d\n", c == d);
    return 0;
}
Text
0.100000001 + 0.200000003 = 0.300000012
0.3f = 0.300000012
equal: 1

So a program that compares float sums to a constant may pass its tests and fail when the type is changed to double, or the reverse. The equality is an accident of rounding, not a property worth testing for. On a platform that evaluates floating-point expressions with extended precision, such as 32-bit x86 with the x87 unit, intermediate results may carry 64 bits of significand, and the answer can differ again. C reports the evaluation mode through FLT_EVAL_METHOD in float.h, which is 0 on x86-64 with SSE2.

Errors accumulate

A single rounding error is tiny, about one part in 10 to the 16 for a double, but it adds up. Add 0.1 ten times in a loop and the total is not 1.

accumulate.cc
#include <stdio.h>

int main(void)
{
    double sum = 0.0;
    for (int i = 0; i < 10; i++) {
        sum += 0.1;
    }
    printf("sum = %.17g\n", sum);
    printf("sum == 1.0: %d\n", sum == 1.0);
    return 0;
}

Each addition rounds, and the rounding errors do not cancel exactly. After ten steps the sum sits one step below 1.0.

Text
sum = 0.99999999999999989
sum == 1.0: 0

A loop that uses x != 1.0 as a stopping test would never stop, or would run one iteration too many or too few. A loop controlled by a floating-point equality is a common source of bugs, and the safer form is an integer counter that computes the value, such as x = i * 0.1, which has one rounding error instead of accumulating them.

What to do about it

  1. Never test floating-point results for exact equality unless you know the values are exactly representable, such as small integers, halves and other dyadic fractions. Compare with a tolerance, as the post on epsilons and ULPs shows.

  2. Use integers for exact decimal quantities. Store money in cents, and durations in milliseconds, as integers. Decimal arithmetic libraries and _Decimal64 in the C extension for decimal floating point also avoid the issue, since they use base 10.

  3. Print enough digits when debugging. Use %.17g for doubles and %.9g for floats, so the value you see is the value that is stored.

  4. Use a counter, not accumulation, for loops. Compute x = start + i * step from an integer i.

  5. Sum in a stable way. For long sums, compensated summation such as Kahan's method or sorting by magnitude reduces the error growth.

Common mistakes

  • Writing if (x == 0.3) after any arithmetic on x.

  • Using a float or double loop variable with != or == as the termination test.

  • Assuming a value that prints as 0.3 is exactly 0.3.

  • Storing currency in double and rounding at the end, which still accumulates and can disagree with an accounting system.

  • Comparing the result of a calculation in float with a double literal, since 0.1f == 0.1 is false.

Taggedcbeginner
Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.