Glossary / Floating-point arithmetic
Floating-point arithmetic
JavaScript Number arithmetic uses IEEE 754 binary64 values. Many decimal fractions, including 0.1, have no finite binary representation, so they are stored as nearby approximations. Arithmetic then rounds intermediate results, producing values such as 0.30000000000000004. This is a representation property, not a JavaScript-specific arithmetic defect.
Error, comparison, and rounding
0.1 + 0.2 === 0.3; // false
For scientific calculations, use numerical methods with known error bounds. For approximate comparison, define an absolute and/or relative tolerance that matches the scale and domain. Do not blindly compare against Number.EPSILON: representable spacing grows with magnitude. NaN, positive/negative infinity, signed zero, overflow, and underflow are also part of Number semantics.
For money, binary floating point may be unsuitable when exact decimal accounting is required. Common strategies include storing integer minor units or using a decimal arithmetic type/library. Define rounding mode and the point at which rounding occurs; “round every step” and “round only at the end” can produce different totals. Formatting with toFixed returns a string and does not make the internal value exact.
Reordering additions can change the rounded result, especially when adding values of very different magnitudes. For large sums, use algorithms designed to reduce accumulated error, if accuracy requirements justify the complexity.
Interview questions
- Why is 0.1 + 0.2 not exactly 0.3? Decimal fractions are approximated in binary, and the sum is rounded.
- Does
toFixedrepair precision? No; it formats a rounded string representation. - How handle money? Use explicit decimal-safe representation and rounding rules.
- Is exact equality always wrong for Numbers? No; it is appropriate for exact discrete values and known constants, but often wrong for computed approximations.