Key points
- JavaScript numbers are binary floating point: 0.1, 0.2 and 1.005 aren’t stored exactly, hence
0.1 + 0.2 = 0.30000000000000004. toFixed()returns a string and rounds the value actually stored, so(1.005).toFixed(2)gives “1.00”. To round reliably, correct the representation error before rounding.- For money, calculate in integer cents, round once in a deliberate place, and format with
Intl.NumberFormatonly for display.
A cart total showing $81.799999, a discount that’s a cent off the invoice, an if (total === 0.3) that never passes: these bugs turn up on nearly every project where JavaScript handles prices, percentages or measurements. They aren’t logic errors; they come from how computers represent decimal numbers. Once you understand the mechanism, the fixes are simple. Here are the ones we use, and the functions best avoided.
Why 0.1 + 0.2 isn’t 0.3
In JavaScript, every number (apart from BigInt) is an IEEE 754 double-precision float, stored in binary. Plenty of simple decimals have no finite binary form, just as 1/3 has no finite decimal form (0.333…). So 0.1 is stored as the nearest binary value, which is ever so slightly off. Add two of those approximations and the gap becomes visible:
0.1 + 0.2; // 0.30000000000000004
0.1 + 0.2 === 0.3; // false
1.1 * 3; // 3.3000000000000003
19.99 * 100; // 1998.9999999999998
This isn’t a JavaScript flaw: PHP, Python, Java and spreadsheets use the same format and get the same results. The difference is that JavaScript happily prints every digit, and it’s increasingly used for business calculations in the browser.
The practical upshot: a decimal calculation almost always lands very close to the expected result, but rarely exactly on it. Everything else in this article follows from that: round at the right moment, compare with a tolerance, and keep decimals out of money altogether.
toFixed() and Math.round(): handy, but treacherous
The first instinct is toFixed(2). It’s fine for quick display, with two traps we keep finding in code reviews:
(1.005).toFixed(2); // "1.00" (expected "1.01")
(2.345).toFixed(2); // "2.35"
typeof (1.5).toFixed(2); // "string"
(0.5).toFixed(2) + 1; // "0.501", concatenation, not addition
Math.round(1.005 * 100) / 100; // 1, same problem
Math.round(-2.5); // -2 : Math.round rounds halves towards +∞
Trap one: toFixed() returns a string. Use it in a calculation and you get concatenation or text comparison, with no error at all. Trap two: it rounds the value that’s actually stored. 1.005 is stored as 1.00499999999999989…, which quite rightly rounds to 1.00. Correct as far as the machine is concerned; wrong as far as your customer is.
The popular Math.round(x * 100) / 100 trick has exactly the same flaw, since 1.005 * 100 is 100.49999999999999. And Math.round() has one more quirk: halves round towards positive infinity, so Math.round(-2.5) is -2, not -3. On a refund or a negative credit, that can leave you a cent away from the matching positive amount.
Rounding correctly to n decimal places
The idea is to fix the representation error before rounding. toPrecision(15) trims the number to 15 significant digits, the precision a double guarantees for a decimal value, which turns 100.49999999999999 into 100.5. We then work on the absolute value so negatives round symmetrically:
/**
* Rounds x to d decimal places, to nearest, halves away from zero.
* toPrecision(15) wipes out the representation error (100.49999999999999 → 100.5)
* before rounding, without building an exponent-notation string.
*/
function roundTo(x, d = 2) {
const factor = 10 ** d;
const n = Number((Math.abs(x) * factor).toPrecision(15));
return (Math.sign(x) * Math.round(n)) / factor;
}
roundTo(1.005); // 1.01
roundTo(-1.005); // -1.01
roundTo(2.345); // 2.35
roundTo(0.1 + 0.2); // 0.3
roundTo(1e-7); // 0
You’ll often see a variant that builds a string like x + 'e2' and converts it back. It works in simple cases but breaks on numbers that are already in exponent notation: for 1e-7 the string becomes '1e-7e2' and the result is NaN.
For display only, Intl.NumberFormat is the right tool: it rounds and adds separators and the currency symbol for the locale (maximumFractionDigits, style: 'currency'). Keep it for display and never feed its output back into a calculation: it’s a localised string, possibly with non-breaking spaces or a decimal comma.
For money: calculate in cents
On our e-commerce and SaaS projects the rule is simple: an amount never travels as a decimal. It’s stored, sent and calculated in integer cents, as most payment APIs do, Stripe included. Integers are exact up to Number.MAX_SAFE_INTEGER, far beyond any shopping cart.
// Cart: every amount in cents (integers), from start to finish
const lines = [
{ label: 'T-shirt', priceCents: 1999, qty: 3 },
{ label: 'Badge', priceCents: 410, qty: 2 },
];
const subtotal = lines.reduce((s, l) => s + l.priceCents * l.qty, 0); // 6817
const tax = Math.round(subtotal * 0.2); // one rounding step, where you decide: 1363
const total = subtotal + tax; // 8180
// Convert to currency units only for display
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
usd.format(total / 100); // "$81.80"
// User input "12.50" (or "12,50" from a European keyboard): convert to cents
const toCents = (input) => Math.round(Number(input.replace(',', '.').trim()) * 100);
toCents('12.50'); // 1250
Two more rules go with cents. Round once, in a deliberate, documented place: is tax calculated per line or on the total? Both are legitimate depending on the context, but they don’t always land on the same cent, and the front end has to match the back office and the invoice exactly. And the calculation that counts happens on the server: the browser shows an estimate, the server recalculates from prices in the database, never from a total sent by the client.
For heavier needs (three-decimal currencies, exchange rates, chained financial calculations), a decimal library such as decimal.js or big.js works in base 10 and sidesteps all of this, at the cost of a clunkier syntax.
Comparing and parsing numbers: the last traps
Since two equivalent calculations can differ in the last digit, never compare two computed decimal results with ===. Compare with a tolerance that fits your domain (a millionth for measurements, half a cent for money), or round both sides before comparing. With amounts in integer cents, === is perfectly reliable again.
// Compare two computed results with a tolerance
const nearlyEqual = (a, b, tolerance = 1e-9) => Math.abs(a - b) <= tolerance;
nearlyEqual(0.1 + 0.2, 0.3); // true
// Input: Number() is strict, parseFloat() stops at the first unexpected character
Number('12,50'); // NaN
parseFloat('12,50'); // 12 : the decimals vanish silently
Number(''); // 0 : an empty field isn't "zero"
Number.isFinite(Number('abc')); // false : the check to run before any maths
Parsing input is the other source of bugs. A European user types a comma; a field can be empty; a paste can bring along a space or a currency sign. Normalise the input, convert with Number(), and check with Number.isFinite() before doing any maths. With an <input type="number">, read valueAsNumber, which returns NaN for invalid input rather than a string.
Finally, write a handful of unit tests with the values that bite: 1.005, 2.345, -2.5, 0.1 + 0.2, 1e-7, an empty field, input with a comma. They’re always the same ones, and they catch in seconds a regression a customer would take weeks to report.
FAQ
Why not just use toFixed everywhere?
Because it returns a string and rounds the stored binary value, which gives surprises like “1.00” for 1.005. It’s acceptable for quick display, but not for calculations or for an amount that has to match an invoice.
Does PHP have the same problem?
Yes, PHP uses the same number format. How round() treats these edge cases has varied between PHP versions; the rule of integer cents (or a decimal library such as BCMath) applies just as much on the server.
Should prices be stored in cents in the database?
That’s what we recommend: an integer column in cents, or an exact DECIMAL type in SQL. Avoid FLOAT or DOUBLE columns for money; they bring back exactly the problem described here.
Shopping carts, online quotes, SaaS billing: we build applications that get the maths right to the cent, in the browser and on the server, with the tests to prove it.



