Question presented to candidate: "If I type 0.1 + 0.2 into a JavaScript console, what do I get, and why? And how would you correctly compare two floating-point numbers for equality in real code?"
What a strong answer should cover:
- 📌 Interview term: IEEE-754 double-precision floating point — every JavaScript
numberis stored in this 64-bit binary format, which can only exactly represent certain fractional values (those expressible as a sum of powers of two). Most decimal fractions, including0.1and0.2, have no exact binary representation and must be rounded to the nearest representable double. - 📌 Interview term: the real answer —
0.1 + 0.2genuinely evaluates to0.30000000000000004, not0.3, because both operands are already-rounded approximations, and their sum's rounding compounds the error. Verified directly via.toPrecision(20), showing the actual stored bits differ from the mathematically exact0.3. - A precise answer names that this is not unique to JavaScript — it affects every language using IEEE-754 doubles (Python, Java, C, Go), since it is a property of the number format itself, not a JavaScript-specific bug.
- 📌 Interview term:
Number.EPSILON— the smallest representable difference between1and the next larger double; the standard correct way to compare floats for "close enough" equality isMath.abs(a - b) < Number.EPSILON(or a domain-appropriate tolerance), never===. - A precise answer names a real counter-example:
0.5 + 0.25 === 0.75is genuinelytrue, because0.5and0.25are both exact powers of two — the bug only affects fractions that are not powers of two, not "all floating-point math."
Clarifying questions expected:
- None — this is a definitional/technical question; precisely naming the IEEE-754 mechanism (not just "floating point is imprecise") is the strong signal.
Code / implementation expected: Optional — showing the toPrecision(20) output and the Number.EPSILON comparison fix demonstrates real understanding beyond reciting "floats are weird."