Handle money in JS with integer cents
Store prices as integer cents so totals add without the 0.1 + 0.2 drift, and format with Intl.NumberFormat only for display.
You add 0.1 + 0.2 in the console and get 0.30000000000000004. Then your cart total fails an equality check, even though the formatted number on the screen looks right.
console.log(0.1 + 0.2) // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3) // false
const prices = [0.1, 0.2, 0.3]
const sum = prices.reduce((total, p) => total + p, 0)
console.log(sum, sum === 0.6) // 0.6000000000000001 falseJavaScript numbers are binary floating point, and 0.1 has no exact binary form: 0.1.toPrecision(20) prints 0.10000000000000000555.
Each addition carries that tiny error forward, and JavaScript neither throws nor warns. Three prices that add up to 0.6 on paper give 0.6000000000000001, and === 0.6 is false.
Keep the cents as integers
I store prices as whole cents. Integer arithmetic stays exact as long as the inputs and results stay within the safe integer range. I put the unit in the name, as in priceCents, so nobody divides twice.
const cents = [10, 20, 30]
const total = cents.reduce((sum, c) => sum + c, 0)
console.log(total, total === 60) // 60 trueThe total is 60, and the equality check passes.
Quantities stay exact too: 3 * 1999 is 5997, which formats as $59.97.
Accept cents from your API when possible. If you receive a decimal string such as "4.35", validate it as a dollar amount with at most two fractional digits and convert its digits to cents. For calculations that produce fractions of a cent, use decimal arithmetic and apply the rounding rule your application requires.
Format only for display
Divide by 100 at the last step and let Intl.NumberFormat write the currency. The style and currency options are all the call needs.
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })
console.log(usd.format(total / 100)) // $0.60
console.log(Number.MAX_SAFE_INTEGER) // 9007199254740991The screen shows $0.60, with the symbol, the separator and two decimals supplied by Intl.
The drifted float 0.6000000000000001 also formats as $0.60, so the screen never shows the error. It shows up in a comparison or in a sum of sums. I keep total as the cents integer in state and in anything I send, and divide only when I draw it.
Past Number.MAX_SAFE_INTEGER, distinct integers can round to the same Number: Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 is true. Near that ceiling, dividing by 100 can round away a cent. For those amounts, pass an exact decimal string to Intl.NumberFormat.format() on runtimes that support it.