Floating-Point Numbers
How computers store real numbers with IEEE 754, why 0.1 + 0.2 isn't 0.3, comparing with tolerance, NaN and Infinity, and handling money.
What is it?
Most languages store non-integer numbers as floating-point values following the IEEE 754 standard. A 64-bit "double" (JavaScript's number, Python's float, Java's double) is a binary version of scientific notation: a sign, an exponent and about 15–17 significant decimal digits of precision.
Because it's binary, many simple decimal fractions can't be stored exactly. 0.1 in binary is an infinitely repeating fraction, just like 1/3 is 0.333… in decimal. The computer stores the nearest representable value, so small errors appear:
0.1 + 0.2 gives 0.30000000000000004, not 0.3.
This isn't a bug in any language; it's how the format works. The practical consequences:
- Don't compare floats with ==; check whether they're close enough. - Know the special values: Infinity, -Infinity, -0 and NaN ("not a number"), which is not even equal to itself. - Don't store money in floats. Use integer cents or a decimal type.
Explain like I'm 10
Floating point is like writing every number with a fixed number of digits on a calculator display. You can show huge or tiny numbers by moving the decimal point, but a number like 1/3 never fits exactly; it gets cut off. Binary floats have the same problem with numbers like 0.1.
Examples
The classic surprise, and how to compare safely
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
function nearlyEqual(a, b, tolerance = 1e-9) {
return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));
}
console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 (2^53 - 1)
console.log(9007199254740992 + 1); // 9007199254740992 (precision lost)NaN, Infinity and money (Python)
import math
from decimal import Decimal
nan = float("nan")
print(nan == nan) # False: NaN never equals anything
print(math.isnan(nan)) # True: the correct check
print(float("inf") > 1e308) # True
print(math.isclose(0.1 + 0.2, 0.3)) # True (relative tolerance 1e-09)
# Money: floats drift, decimals and integer cents don't
print(sum([0.1] * 10)) # 0.9999999999999999
print(sum([Decimal("0.10")] * 10)) # 1.00
price_in_cents = 1999 # $19.99 as an integer
print(price_in_cents * 3) # 5997 cents, exactBuild Decimal from strings, not floats: Decimal(0.1) faithfully copies the float's error. In JavaScript, use integer cents or a decimal library, and Number.isNaN rather than === NaN.
How it works
A 64-bit IEEE 754 double has three fields:
- 1 sign bit - 11 exponent bits: scale the number by a power of two - 52 fraction bits: the significant digits (53 bits of precision counting an implicit leading 1)
The value is roughly (-1)^sign × 1.fraction × 2^(exponent − 1023). Because the exponent moves the binary point, doubles cover an enormous range (about 10^-308 to 10^308), but the gap between neighbouring values grows with the magnitude. Near 1 the gap is about 2.2 × 10^-16 (machine epsilon, Number.EPSILON); near 10^16 it's 2.
Every arithmetic operation rounds its exact result to the nearest representable double. Rounding errors are tiny per step but can accumulate over many steps, and subtracting two nearly equal numbers can wipe out most of the significant digits (catastrophic cancellation).
Special bit patterns encode ±Infinity (overflow, or 1/0 in JS), NaN (invalid results like 0/0 or sqrt(-1)) and -0.
64-bit double layout
| s | exponent (11) | fraction (52) |
63 62 52 51 0
0.1 stored as 0.1000000000000000055511151231257827...
0.2 stored as 0.2000000000000000111022302462515654...
sum rounds to 0.3000000000000000444089209850062616...
0.3 stored as 0.2999999999999999888977697537484345...Why does it exist?
Scientific and graphics work needs both astronomically large and tiny numbers, fast. Fixed-point or arbitrary-precision decimal arithmetic can't do that efficiently in hardware. IEEE 754 (1985) standardised a binary format that CPUs and GPUs implement directly, so results are fast and consistent across machines, at the cost of exactness for decimal fractions.
When to use it
Floats are right for measurements and continuous quantities where tiny relative errors don't matter: physics, statistics, graphics, machine learning, sensor data, percentages for display. Always compare with a tolerance, and round only when presenting the result.
When not to use it
Don't use binary floats for money, or anywhere exact decimal results are legally or logically required (invoices, tax, ledgers). Use integer minor units (cents), Decimal (Python), BigDecimal (Java) or a decimal library. Don't use floats for large integer IDs: in JavaScript, values above 2^53 lose precision, so use strings or BigInt.
Common mistakes
Comparing floats with
==/===instead of using a tolerance (math.isclose, an epsilon check).Storing currency as floats, so totals drift by fractions of a cent and fail to reconcile.
Checking for NaN with
x === NaNorx == float('nan'), which is always false; useNumber.isNaNormath.isnan.Using a fixed absolute epsilon like
1e-9for numbers of any size, which is far too strict for large values and too loose for tiny ones.Parsing large numeric IDs from JSON into JavaScript numbers and silently corrupting them above 2^53.
Practice exercises
- Easy:
In Python and JavaScript, print
0.1 + 0.2,1 / 3 * 3,0.1 * 3and1e16 + 1. Explain each result. - Medium:
Write a function that splits a bill of $100.00 among 3 people using integer cents, so the parts add up exactly to the total (e.g. 3334 + 3333 + 3333).
- Hard:
Sum the numbers 0.1 ten million times with a naive loop, then with Kahan summation (or Python's
math.fsum). Compare both results with the exact answer and explain the difference.
Interview questions
Why does 0.1 + 0.2 not equal 0.3 in most languages?
Floats are stored in binary, where 0.1 and 0.2 are infinitely repeating fractions. Each is rounded to the nearest double, and their sum rounds to a value slightly above 0.3 (0.30000000000000004), which differs from the double nearest to 0.3.
How should you compare two floating-point numbers?
Check whether their difference is within a tolerance, usually relative to their magnitude (with an absolute floor near zero). Use math.isclose in Python or a helper like Math.abs(a - b) <= eps * Math.max(1, |a|, |b|) in JavaScript.
What is IEEE 754?
The standard for binary floating-point arithmetic used by virtually all hardware and languages. It defines formats (32-bit float, 64-bit double), rounding rules and special values like Infinity, -0 and NaN.
How many significant digits does a double have?
53 bits of binary precision, which is about 15 to 17 significant decimal digits.
What is NaN, and why is `NaN === NaN` false?
NaN (Not a Number) represents an undefined result such as 0/0. IEEE 754 defines it as unordered and unequal to every value, including itself, so you must test it with Number.isNaN or math.isnan.
What is machine epsilon?
The gap between 1.0 and the next larger representable double, about 2.22e-16 (2^-52). It indicates the relative precision of the format; JavaScript exposes it as Number.EPSILON.
How should money be represented?
As integers in the smallest unit (cents), or with a decimal type such as Python's Decimal or Java's BigDecimal, with explicit rounding rules. Never as binary floats, whose rounding errors accumulate.
What is `Number.MAX_SAFE_INTEGER` and why does it exist?
It's 2^53 - 1 (9007199254740991), the largest integer such that every integer up to it can be represented exactly by a double. Beyond it, some integers can't be represented, so arithmetic silently rounds. Use BigInt for larger integers.
What does `1 / 0` produce in JavaScript and in Python?
In JavaScript it's Infinity, as IEEE 754 specifies. Python raises ZeroDivisionError for both int and float division by zero, though float('inf') exists and overflow in some operations yields inf.
What is catastrophic cancellation?
A large loss of precision when subtracting two nearly equal floating-point numbers: the leading digits cancel and the result is dominated by earlier rounding errors. Reformulating the calculation usually avoids it.