Decimal
Example
const total = 0.1 + 0.2;
console.log(total === 0.3); // falseconst totalCents = 10 + 20;
console.log(totalCents === 30); // trueBinary floats can't store most decimal fractions exactly, so money is kept in integer cents.
Common mistakes
- Storing prices as floats and getting totals like 0.30000000000000004.
Key points
- Money is stored as integer minor units, like cents, or a decimal type, not binary floats.
- Floats are compared with a tolerance like
Number.EPSILON, not===. - Money columns in SQL use
DECIMALorNUMERIC, notFLOAT.
Interview questions
Why can't computers store 0.1 exactly?
Numbers are stored in binary, and 0.1 has an infinite binary fraction, so it is rounded to the closest value that fits.
Should I use toFixed to fix float errors?
toFixed to fix float errors?Only for display. toFixed returns a rounded string; do the math in integers or a decimal library.