JavaScript Intermediate
What is 0.1 + 0.2 in JavaScript? Why? How to avoid floating-point issues?
Result of 0.1 + 0.2
0.1 + 0.2 === 0.3 // false
0.1 + 0.2 // 0.30000000000000004
Why?
JavaScript uses IEEE 754 double-precision floats. Neither 0.1 nor 0.2 can be represented exactly in binary, causing rounding errors when added.
Solutions
1. Epsilon comparison
Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON // true
2. Integer arithmetic
(0.1 * 10 + 0.2 * 10) / 10 // 0.3
3. toFixed()
parseFloat((0.1 + 0.2).toFixed(10)) // 0.3
4. Use a library
Use decimal.js or big.js for arbitrary precision.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
