Predict the output of the following javascript code
console.log(0.1 + 0.2 == 0.3);
Quiz Explanation
In JavaScript, due to the way floating-point arithmetic is handled by computers, operations involving floating-point numbers may not always produce exact results.
In this case, 0.1 + 0.2
will not exactly equal 0.3
due to precision issues inherent in floating-point arithmetic.
So, the expression 0.1 + 0.2 == 0.3
will evaluate to false
.
To mitigate this issue, it's often recommended to compare floating-point numbers using a tolerance value, such as:
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
This will account for small differences caused by floating-point precision and return true
if the difference is within an acceptable tolerance.