Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 171 ยท Variables and Types

Floating-Point Numbers

Learn C++ float, double and long double, why 0.1 + 0.2 != 0.3, how to compare floating-point values safely, NaN and infinity, and std::numbers constants.

Whenever a value can have a fractional part (a temperature, a price per kilo, a physics position, a probability), you reach for a floating-point type. C++ has three: float, double and long double. They can represent astonishingly large and small numbers, from about 10โปยณโฐโธ to 10ยณโฐโธ for double, and they are fast because the processor has dedicated hardware for them.

The catch is that floating-point numbers are approximations. Most decimal fractions, including something as simple as 0.1, cannot be stored exactly. Programs that ignore this print strange results, take wrong branches, and occasionally lose money. This lesson shows exactly where the errors come from and the professional habits for living with them.

The three types

On every mainstream platform, float and double follow the IEEE 754 standard. long double varies more:

Type Size here Significant decimal digits Approximate range Literal
float 4 bytes (32 bits) about 6โ€“7 ยฑ3.4 ร— 10ยณโธ 2.5f
double 8 bytes (64 bits) about 15โ€“16 ยฑ1.8 ร— 10ยณโฐโธ 2.5
long double 16 bytes on x86 Linux (80-bit extended), 8 on MSVC 18 here, 15 on MSVC ยฑ1.2 ร— 10โดโนยณยฒ here 2.5L

Use double by default. It is the type of unsuffixed literals like 3.14, the type the <cmath> functions are designed around, and on modern CPUs it is usually just as fast as float for scalar math. Choose float when you store millions of values and memory or bandwidth matters (graphics, audio, machine learning, game physics), and accept the lower precision knowingly. long double is rarely needed and isn't portable: with Microsoft's compiler it is the same as double.

Floating-point literals can be written several ways:

C++
double a = 3.0;       // a decimal point makes it floating point
double b = 3.;        // legal, but easy to miss
double c = 6.02e23;   // scientific notation: 6.02 ร— 10^23
double d = 1.5e-9;    // 0.0000000015
float  e = 0.25f;     // f suffix: a float literal
double f = 0x1.8p1;   // hexadecimal float (C++17): 1.5 ร— 2^1 = 3.0

C++23 also added optional fixed-format types in <stdfloat>, such as std::float16_t, std::float32_t and std::bfloat16_t. GCC supports them on x86-64, but they are new and not universal, so this course sticks to float and double.

How floating point stores numbers

A floating-point value is stored like scientific notation in binary: a sign, a significand (the digits) and an exponent (where the binary point goes). A double has 52 stored significand bits (53 with an implicit leading 1), and that fixed number of bits is the whole story behind its behavior:

  • Precision is relative, not absolute. Near 1.0, neighboring doubles are about 2.2 ร— 10โปยนโถ apart. Near one billion, they are about 1.2 ร— 10โปโท apart. The gap grows with the size of the number.
  • Only fractions with a power-of-two denominator are exact. 0.5, 0.25 and 0.375 are stored exactly. 0.1 is 1/10, and 10 has a factor of 5, so 0.1 repeats forever in binary, just like 1/3 repeats forever in decimal. The stored value is the nearest representable number, which is slightly more than 0.1.
  • Whole numbers are exact up to a point: every integer up to 2โตยณ (about 9 ร— 10ยนโต) fits exactly in a double, but only up to 2ยฒโด (16,777,216) in a float.
C++ What is really stored

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

By default std::println prints the shortest decimal text that converts back to exactly the same double. That is why 0.1 looks clean while 0.1 + 0.2 shows 0.30000000000000004: the sum is a different double from the one nearest to 0.3. Asking for 20 decimals reveals the true stored values. And at 2ยฒโด, adding 1 to a float does nothing, because the next representable float is 16,777,218.

Rounding errors add up

Each operation rounds its result to the nearest representable value. One rounding is tiny, but long chains of operations accumulate error:

C++ Adding a dime ten times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

After a million additions, the float total is 100958.34, off by almost a thousand. Once the running sum is large, each 0.1f gets rounded to a much coarser step. The integer version is exact. That is the rule for money: store an integer number of the smallest unit (cents) and format it only for display.

Ways to reduce accumulated error when you do need floating point:

  • Use double instead of float.
  • Compute from a counter instead of adding repeatedly: x = start + i * step beats x += step.
  • Avoid subtracting nearly equal values (catastrophic cancellation) when a rearranged formula exists.

Comparing floating-point values

Because results are approximations, == on computed values is almost always a bug. Compare with a tolerance instead. A fixed tolerance (std::abs(a - b) < 1e-9) fails for very large or very small numbers, so a robust check combines an absolute and a relative tolerance:

C++ Comparing with a tolerance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice that 1e-20 and 2e-20 count as "close" even though one is twice the other: both are below the absolute tolerance, so the function treats them as zero. That is usually what you want for values that should be zero but picked up rounding noise. There is no universal tolerance. Pick one that matches the precision of your data: millimeters for a CAD program, cents for prices, the sensor's resolution for measurements. std::numeric_limits<double>::epsilon() (about 2.2 ร— 10โปยนโถ) is the gap between 1.0 and the next double. It is a building block for relative tolerances, not a ready-made tolerance on its own.

Comparing with == is fine when values are exact by construction: small whole numbers, values you assigned and never computed, or checking against 0.0 that you stored yourself. The problem is comparing results of arithmetic.

Infinity, NaN and negative zero

IEEE floating point has special values that keep calculations going instead of crashing:

  • Infinity (inf): the result of overflow, or of dividing a nonzero number by zero.
  • NaN, "not a number": the result of meaningless operations like 0.0 / 0.0, std::sqrt(-1.0) or inf - inf.
  • Negative zero (-0.0): equal to 0.0 under ==, but 1.0 / -0.0 is -inf.

NaN has a unique and important property: it compares unequal to everything, including itself. x == x is false when x is NaN, and any <, > or == involving NaN is false. Use std::isnan and std::isinf (or std::isfinite) from <cmath> to test for them:

C++ The special values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

You may see -nan printed for 0/0 on x86 machines: the processor's default NaN has its sign bit set, and the formatter shows that bit. The sign of a NaN carries no meaning.

Three cautions about special values:

  • The C++ standard itself calls division by zero undefined behavior. IEEE 754 platforms (where std::numeric_limits<double>::is_iec559 is true, which is every mainstream one) define the results shown above, but don't rely on dividing by zero as a feature. Check divisors.
  • Converting a floating-point value to an integer type when the value doesn't fit, or is NaN or infinity, is undefined behavior on every platform. Check the range before you convert (see Type Conversions and Casts).
  • A single NaN silently poisons every calculation it touches, and comparisons with it are false, so a sort or a max over data containing NaN can give nonsense. Validate inputs at the boundary.

Mathematical constants with <numbers>

For decades, C++ programmers wrote their own const double PI = 3.14159...; or used the non-standard M_PI macro. C++20 added the <numbers> header with correctly rounded constants:

C++ std::numbers in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The constants include pi, e, sqrt2, sqrt3, phi, ln2, ln10, log2e, log10e, inv_pi, inv_sqrtpi, inv_sqrt3 and egamma. Each is a double; the _v versions (std::numbers::pi_v<float>) give the same constant in another floating type. They are constexpr, so they work in compile-time constants.

Formatting floating-point output

std::format and std::println give you full control over how numbers look:

Spec Meaning std::numbers::pi prints
{} shortest exact round-trip 3.141592653589793
{:.2f} fixed, 2 decimals 3.14
{:.3e} scientific, 3 decimals 3.142e+00
{:.4g} general, 4 significant digits 3.142
{:10.2f} width 10, right-aligned 3.14

Formatting with std::format and std::print covers every option. With std::cout, the same control comes from std::fixed and std::setprecision in <iomanip>, which the I/O Streams in Depth lesson explains.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is 0.1 + 0.2 == 0.3 false for doubles?

    Decimal fractions like 1/10 repeat forever in binary, so each value is rounded. The sum lands on 0.30000000000000004, a neighbor of the double closest to 0.3.
  2. 2. double x = std::sqrt(-1.0); What does x == x evaluate to?

    sqrt(-1.0) returns NaN, and NaN compares unequal to everything, including itself. Use std::isnan(x) to test for it.
  3. 3. Which is the best way to store a bank balance?

    Money needs exact decimal arithmetic. Floating-point types can't store most cent values exactly and errors accumulate; an integer number of cents is exact.
  4. 4. What does 16777216.0f + 1.0f give?

    A float has 24 significand bits, so above 2^24 = 16,777,216 it can only store even numbers. 16,777,217 rounds back to 16,777,216.
  5. 5. Which default type should you use for a fractional value in ordinary code?

    double is the type of literals like 3.14 and of the <cmath> functions, gives about 15 digits, and is fast. Use float only when storage of many values matters.

Summary

  • float (~7 digits), double (~15โ€“16 digits, the default) and long double (platform-dependent) store approximate real numbers.
  • Values are binary fractions with a fixed number of bits: 0.1 is not exact, precision is relative, and integers are exact only up to 2ยฒโด (float) or 2โตยณ (double).
  • Rounding errors accumulate. Use double, compute from counters, and use integer cents for money.
  • Never compare computed results with ==; use a tolerance that combines absolute and relative checks.
  • Infinity and NaN propagate through calculations. NaN is unequal to itself: test with std::isnan. Converting NaN, infinity or out-of-range values to integers is undefined behavior.
  • <numbers> (C++20) provides std::numbers::pi, e, sqrt2 and more; std::println("{:.2f}", x) controls decimals.

Next: Characters and Booleans, where char turns out to be a small integer and bool hides a few surprising conversions.