0

What will be the output of the following code and why?

author
subina kallyani
easy
2
39
console.log(0.1 + 0.2 === 0.3);
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.2 is approximately 0.30000000000000004, not exactly 0.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); // true


Click to Reveal Answer

Tap anywhere to see the solution

Revealed

Comments0
    What will be the output of the following code and why? - number | EBAT