JavaScript · The language round
Why does 0.1 + 0.2 not equal 0.3?
Short answer
JavaScript numbers are IEEE 754 doubles, so many decimal fractions cannot be represented exactly. Use an epsilon check or integer arithmetic for comparisons, and BigInt for large integers.
This is not a JavaScript bug. Binary floating point cannot represent some base-10 fractions exactly, just as base 10 cannot represent one third exactly.
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
console.log(Number.EPSILON); // 2.220446049250313e-16
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // truePractical approaches
- Compare with a tolerance such as
Number.EPSILONinstead of strict equality - Store money in integer paise or cents, then format for display
- Use a decimal library for financial calculations that need exact base-10 behaviour
- Use
BigIntfor integers beyondNumber.MAX_SAFE_INTEGER
const priceInPaise = 1999;
const quantity = 3;
const totalInPaise = priceInPaise * quantity;
console.log((totalInPaise / 100).toFixed(2)); // "59.97"Number.MAX_SAFE_INTEGER is the largest integer that can be represented exactly. Beyond that, integer arithmetic can silently lose precision. BigInt avoids that but cannot be mixed with regular numbers without explicit conversion.
JSON.stringify throws on BigInt values. Convert them to strings before sending them over JSON.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is `0.1 + 0.2` not exactly `0.3`?
- 2How do you compare floating-point numbers safely?
- 3What is `Number.MAX_SAFE_INTEGER`?
- 4When would you use `BigInt` instead of `Number`?
Say it in the interview
JavaScript uses IEEE 754 double-precision numbers, so fractions like 0.1 cannot be stored exactly. Adding them can produce a tiny rounding error, which is why the result is not strictly equal to 0.3. For comparisons I use an epsilon tolerance. For money I store integer paise or cents. For very large integers I use BigInt, remembering that it cannot be mixed freely with Number or serialized directly to JSON.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.