console.log(0.1 + 0.2 === 0.3);0
What will be the output of the following code and why?
subina kallyani
easy
2completed
39
Answer
The output will be: false
This happens due to the way floating-point arithmetic works in JavaScript (and most programming languages).
- Numbers like 0.1 and 0.2 cannot be represented exactly in binary floating-point format.
- The actual result of
0.1 + 0.2is approximately0.30000000000000004, not exactly0.3. - Therefore:
0.1 + 0.2 === 0.3 // false
Correct Way to Compare Floating-Point Numbers:
Instead of strict equality, use a small tolerance (epsilon) to compare:
const epsilon = 0.000001;
console.log(Math.abs(0.1 + 0.2 - 0.3) < epsilon); // trueClick to Reveal Answer
Tap anywhere to see the solution
Revealed
Comments0