skip to content

Why does a C++ float holding 0.1f compare unequal to the literal 0.1, and how should floating values be compared?

level: middleimportance: should knowfreq 45%

answer

  1. the literal has its own type
  2. unsuffixed means double
  3. the float is widened, not the literal narrowed
  4. two different roundings of 0.1
  5. tolerance scaled to the magnitude

basics

~20 s

The literal 0.1 is a double, so the float is converted to double before ==. 0.1f widened is 0.10000000149011612, not the double nearest 0.1, so they differ. Compare floats against float literals, and compare computed values with a tolerance.

solid answer

~40 s

An unsuffixed floating literal like `0.1` has type `double`; `0.1f` is a `float`. In `gain == 0.1` the usual arithmetic conversions convert the `float` to `double`, and widening is exact: it reproduces the float's own rounding of 0.1, `0.10000000149011612`, which is not the double closest to 0.1. So the comparison is false, and Clang even says so: "floating-point comparison is always false; constant cannot be represented exactly in type 'float'". Write the literal in the variable's type (`0.1f`), and keep `float` code in `float` — `gain * 2.0` silently computes in `double`. For values produced by arithmetic, exact equality is fragile even within one type (`0.1 + 0.2 == 0.3` is false), so compare against a tolerance scaled to the magnitude of the values, not a bare `std::numeric_limits<double>::epsilon()`.

code

cpp · 16 lines
cpp
#include <cmath>
#include <cstdio>
#include <type_traits>

int main() {
    float gain = 0.1f;
    std::printf("gain == 0.1f -> %d\n", gain == 0.1f);
    std::printf("gain == 0.1  -> %d\n", gain == 0.1);   // float widened to double
    std::printf("gain as double = %.17g\n", static_cast<double>(gain));
    static_assert(std::is_same_v<decltype(gain * 2), float>);
    static_assert(std::is_same_v<decltype(gain * 2.0), double>);

    double a = 0.1 + 0.2, b = 0.3;
    bool close = std::fabs(a - b) <= 1e-9 * std::fmax(std::fabs(a), std::fabs(b));
    std::printf("a == b -> %d, close -> %d\n", a == b, close);
}

go deeper

for a junior

Know that 0.1 is a double, 0.1f a float, and that computed floating values should not be compared with ==.

for a middle

Explain how the usual arithmetic conversions widen the float and why the widened value is not the double nearest 0.1.

for a senior

Catch accidental double literals in float hot paths and choose tolerances from the data's resolution rather than from epsilon.

for a principal

Decide whether a codebase standardises on float or double for a domain, and how its tests compare floating results.

## Literals have types too In C++ a floating literal without a suffix is a `double`. The suffix `f` or `F` makes it a `float`, and `l` or `L` makes it a `long double`. So `0.1` and `0.1f` are different values: each is the nearest representable number to one-tenth in its own type, and a `float` has far fewer bits to approximate with. | Spelling | Type | Stored value (IEEE 754 on mainstream targets) | |---|---|---| | `0.1f` | `float` | 0.100000001490116119384765625 | | `0.1` | `double` | 0.1000000000000000055511151231257827… | ## What happens in `gain == 0.1` `==` applies the **usual arithmetic conversions**. When both operands are floating, the one with the lower floating-point conversion rank converts to the other's type, so the `float` becomes a `double`. That widening is exact — every `float` value is also a `double` value — which means it preserves the float's coarse rounding instead of "improving" it. The comparison is then between 0.10000000149011612 and 0.1000000000000000055..., and it is false. Clang diagnoses the pattern by default with `-Wliteral-range`: "floating-point comparison is always false; constant cannot be represented exactly in type 'float'". The fix is to compare like with like: `gain == 0.1f` is true, because both sides are the same rounding. ## Mixed float and double arithmetic The same rule silently changes the precision of whole expressions: - `gain * 2` stays `float`: the integer converts to the floating operand's type. - `gain * 2.0` is a `double` expression; the result is converted back to `float` only if you store it in one. - Passing a `float` to a variadic function such as `std::printf` promotes it to `double` as well. In hot numeric code (physics steps, audio buffers, sensor filters) an accidental `double` literal can mean conversion instructions in the loop and results that differ from a `float`-only computation. Clang's `-Wdouble-promotion` reports implicit float-to-double widening. ## Comparing computed values Even within one type, results of arithmetic carry rounding error. `0.1 + 0.2 == 0.3` is false in `double`, and a `float` has only 24 significand bits (`std::numeric_limits<float>::digits`), so 16777217 is not representable and `16777216.0f + 1.0f` is still 16777216. Practical rules: 1. Compare with a tolerance: `std::fabs(a - b) <= rel * std::fmax(std::fabs(a), std::fabs(b))`, plus a small absolute tolerance when values can be near zero. 2. Pick the tolerance from the problem — sensor resolution, accumulated error of the algorithm — not from `std::numeric_limits<T>::epsilon()`, which is only the gap between 1.0 and the next value. 3. Exact `==` is fine for values that were assigned rather than computed, such as a sentinel or a value copied from elsewhere. 4. `-Wfloat-equal` (GCC and Clang) flags every `==` and `!=` on floating operands when a codebase wants to review them all. ## Seeing the stored value Default formatting hides all of this: `std::cout << gain` prints `0.1`, because six significant digits round the error away. To see what is really stored, print with enough digits to round-trip: - `std::numeric_limits<float>::max_digits10` is 9 and `std::numeric_limits<double>::max_digits10` is 17 for IEEE 754 types; printing that many significant digits (`%.17g`, or `std::setprecision(17)` on a stream) shows the exact rounding. - `std::numeric_limits<T>::digits10` (6 for `float`, 15 for `double`) is the opposite guarantee: how many decimal digits survive a trip into the type and back out. - A debugger or a log that shows `0.1` for both values is not evidence that they are equal. In a sensor pipeline, the practical rule is to choose one floating type per stage, write its literals with the matching suffix, and log values at round-trip precision when diagnosing a comparison that "should" be true. ## What the standard does and does not promise The standard requires three floating types, with `double` at least as precise as `float` and `long double` at least as precise as `double`, and leaves the representation and the accuracy of operations **implementation-defined**. Mainstream platforms use IEEE 754 binary32 and binary64, which `std::numeric_limits<double>::is_iec559` reports. `long double` varies most: on arm64 macOS it is the same 64-bit format as `double`, while other targets use wider formats — never assume extra precision from it.

  • Why is std::numeric_limits<double>::epsilon() a poor general tolerance?
    It is the distance from 1.0 to the next representable `double`, about 2.2e-16. For values near 1e6 the spacing between neighbours is far larger, so an epsilon test degenerates into exact equality; for values near 1e-20 it accepts almost anything. A tolerance has to scale with the magnitude of the operands and reflect how much error the computation can accumulate.
  • When does mixing float and int keep the computation in float?
    When one operand is floating and the other is an integer, the integer converts to the floating operand's type, so `gain * 2` is a `float` expression. Only another floating operand of higher rank, such as the `double` literal `2.0`, widens the computation.

  • 0.1f and 0.1 are the same number stored in different sizes
  • the double literal is narrowed to float before comparing
  • using double everywhere makes == safe for computed values
  • epsilon() is the right tolerance for any comparison
  • long double always gives more precision than double