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.
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:
Note: Number.EPSILON works well when numbers are around magnitude 1, but for larger numbers we might scale EPSILON accordingly.
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.
3. Use Intl.NumberFormat for display
4. Use toFixed() for simple rounding
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!
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)
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