What is 0.1 + 0.2 really in JavaScript? Decimals are stored in binary: see the digits really stored and the safe ways to compare. An interactive 0.1 + 0.2 ≠…
Why it matters
This is the number one trap that makes === fail mysteriously, and the most common source of money and billing bugs. Every time you count prices, weights or percentages with decimals, it lurks. Know the cure and your sums come out right.
The key idea
Decimals are stored in binary, so the result is slightly off
Common mistakes
0.1 + 0.2 === 0.3 says false, though the sum looks right Never use === on a decimal result. Compare with a scaled tolerance: Math.abs(a - b) < Number.EPSILON * Math.max(1, Math.abs(a), Math.abs(b)), or in whole numbers. A bare Number.EPSILON only fits near 1 (see 1.1 × 3).
A shopping total drifts after many decimal additions Every addition can be one step off, and the differences pile up. Keep whole numbers of the smallest unit (cents, grams), compare the whole numbers, and divide only to show them.
After toFixed, the next sum is oddtoFixed gives a string: (0.1 + 0.2).toFixed(2) + 1 becomes '0.301'. Wrap it in Number(...) before counting on.
Try it in this playground
Weigh 0.1 + 0.7 0.7999999999999999: one step below 0.8. The real shape of a total-price bug.
Find a decimal sum that is exact 0.5 + 0.25: halves and quarters are stored exactly, so === holds.
Compare in grams Math.round(kg * 1000) makes a weight a whole number, and whole numbers compare exactly.
Try the 'toFixed' way It compares text. Look at hasil.toFixed(2) + 1 too: a string, not a number.