DEV Community

Cover image for Why does 0.1 + 0.2 === 0.3 return false?
Della Dominic
Della Dominic

Posted on

Why does 0.1 + 0.2 === 0.3 return false?

Javascript uses IEEE 754 floating point representation for storing numbers. This means that some decimal fractions (like 0.1) cannot be represented exactly in binary floating-point format.

decimals not matching

So how DO we work with decimals?

1. Compare with tolerance for equality checks

Taking into consideration the small error difference, Instead of comparing 2 decimals with equality operator we will check if the difference between them is less than the tolerance value.

Javascript provides a static property, Number.EPSILON that represents the smallest difference. Using this we can compare the equality of decimals as shown below:

using tolerance to compare decimals

Note: Number.EPSILON works well when numbers are around magnitude 1, but for larger numbers we might scale EPSILON accordingly.

scale epsilon value

2. Working with Money?

Avoid floating-point arithmetic for financial calculations. Use integers (cents/paise) or dedicated decimal libraries. Always convert to cents, not dollars. This is Recommended in terms of working with billing or payment logic in Fintech Apps.

work with cents

3. Use Intl.NumberFormat for display

format using intl.numberformat

4. Use toFixed() for simple rounding

using toFixed

Note: Can you think what would be the output of below code?

console.log((0.1 + 0.2).toFixed(2) === 0.30);

This will return false since toFixed() returns a string not a number and hence the strict equality check fails!
to.Fixed return string

you can read more about it here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON

Happy learning! cheers✨

Top comments (1)

Collapse
 
della_codes profile image
Della Dominic • Edited

I’m incredibly grateful for the support on my previous post about beginning this learning journey. I may not document everything I study, but I’ll be sharing one meaningful thing I learn along the way. Thank you all for the encouragement — onward and upward.🚀 #day1/100