Understanding IEEE‑754 Floating‑Point Precision Issues in JavaScript
This article explains why JavaScript’s Number type, which follows the IEEE‑754 double‑precision standard, can produce unexpected results such as 0.1 + 0.2 = 0.30000000000000004, demonstrates the binary representation of numbers like 2.5 and 0.1, and offers practical techniques and libraries to mitigate floating‑point errors.
When adding numbers like 0.1 + 0.2 in JavaScript, the console prints 0.30000000000000004, which feels counter‑intuitive.
JavaScript’s sole numeric type Number is implemented using the IEEE‑754 double‑precision binary floating‑point format, a standard shared by many programming languages, and therefore inherits its rounding behavior.
IEEE‑754 represents a value as S + E + M = 64 bits, where S is the sign bit, E the 11‑bit exponent (biased by 1023), and M the 52‑bit mantissa; the actual value is (‑1)^S × 1.M × 2^(E‑1023).
Example 1 – Decimal 2.5: Converting 2.5 to binary yields 10.1. After normalizing to 1.01 × 2^1, the sign bit is 0, exponent becomes 1024, and the mantissa fits within 52 bits, so the value is stored exactly without loss.
Example 2 – Decimal 0.1: Binary conversion produces an infinite repeating fraction 0.0001100110011…. After normalizing and rounding to 52 mantissa bits, the stored value corresponds to 0.10000000000000000555, introducing a small error that propagates when performing arithmetic such as 0.1 + 0.2.
The same process applied to 0.2 yields a similar rounding error, and the sum of the two approximated values results in the observed 0.30000000000000004.
Mitigation strategies: Use built‑in methods to control precision, e.g., x.toFixed(2), parseFloat(x.toPrecision(3)), or Math.round(x). For more demanding cases, employ arbitrary‑precision libraries such as bignumber.js, decimal.js, or big.js.
References include “JavaScript: The Good Parts”, articles on floating‑point traps, and the IEEE‑754 specification.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Beike Product & Technology
As Beike's official product and technology account, we are committed to building a platform for sharing Beike's product and technology insights, targeting internet/O2O developers and product professionals. We share high-quality original articles, tech salon events, and recruitment information weekly. Welcome to follow us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
