Blog Details

blog
about

Your Cart Total Is Off by One Cent

Your Cart Total Is Off by One Cent

The support ticket is one line long: "my total changed after I paid." The cart said $59.97, the confirmation email said $59.98, and the gateway settled $59.97. Nobody can reproduce it locally, because on the developer's machine the numbers agree.

Money bugs in commerce code rarely look like money bugs. They look like a report that does not reconcile, an invoice that is a cent off the order, a refund that leaves a balance nobody can close. The cause is almost always the same three things: a float in the arithmetic, a hardcoded assumption that every currency has two decimals, and a rounding step that runs more than once on the same value.

Where the cent goes first

Binary floating point cannot represent most decimal fractions exactly, and the errors are small enough to hide until they are multiplied. Multiply 1.10 by 3 in JavaScript, Python, or PHP with default floats and the answer is 3.3000000000000003. Add 0.10 and 0.20 and you get 0.30000000000000004. Both print as the number you expected if you format to two places, which is exactly why the bug survives review.

The damage usually lands on the conversion back to cents. Take a price of 4.35 and multiply by 100 to get cents. The float result is 434.99999999999994, and truncating it with int() or parseInt() gives 434. That is one cent gone on every line, and if you are the merchant, it is gone in your favour, which means it compounds into a refund obligation. The same operation on 0.29 yields 28.999999999999996 and 28 cents.

Rounding does not rescue it either. Half-up rounding of 1.005 to two places gives 1.00 in most languages, because the stored value is slightly under 1.005, and PHP's round(2.675, 2) returns 2.67 for the same reason. Any code path where a customer sees a different number than the one you charge started here.

Integers fix it, and then a hidden assumption breaks it

The fix everyone knows is to store money as an integer number of minor units. Payment APIs enforce this anyway. Stripe takes an integer amount in the smallest currency unit, so $19.99 is sent as 1999, and card charges cap out at 12 digits, or 999,999,999,999 minor units.

The assumption hiding inside that pattern is the multiplier. Most code multiplies by 100 and moves on, which works for USD, EUR, GBP, and CAD. It breaks for the currencies where ISO 4217 does not use two decimal places. The Japanese yen and Korean won have no minor unit at all, so 1,500 JPY is sent as 1500. The Kuwaiti dinar, Bahraini dinar, Jordanian dinar, Omani rial, and Tunisian dinar use three decimals, where one dinar is 1,000 fils. The Chilean Unidad de Fomento uses four.

Get the scale wrong in the optimistic direction and you overcharge by a factor of 100. Get it wrong in the other direction and the third decimal of a Kuwaiti price gets silently truncated on every transaction, which is a systematic undercharge that will pass through review because the numbers look reasonable.

Providers also carry legacy exceptions that no clean model predicts. Stripe treats the Icelandic króna as zero-decimal, but requires you to send it as a two-decimal value with the decimals always 00, so 5 ISK is an amount of 500. The Ugandan shilling works the same way, and where proration or tax leaves a fractional amount on an invoice, Stripe rounds to the nearest multiple of 100 and moves the difference to the customer balance.

The practical version: keep the number of decimal places as metadata keyed on the currency code, do not store it as a constant, and test with at least one zero-decimal and one three-decimal currency in the suite.

Round once, then stop

A cart with three lines of $0.99, taxed at 7.25%, produces $0.07 of tax per line if you round each line, for a total of $0.21. Round the tax on the combined $2.97 instead and you get $0.22. Both answers are defensible, and one of them will not match the invoice, the ledger, or the gateway.

The rule that ends the argument is that the customer-facing total is the source of truth, and the line items have to add up to it. That means deciding where rounding happens, writing it down, and making every downstream system read the stored result instead of recalculating. Recalculation is the real culprit. A cart service that rounds per line, an invoice service that rounds per document, and a tax engine that rounds once at the end will disagree on a small percentage of orders, and the disagreements arrive months later as an accounting exception list.

Store the computed amounts at the moment of sale. Subtotal, discount, tax, shipping, and total, each as integer minor units, plus the currency and the number of minor units per major unit. An invoice generated in 2029 should reproduce a 2026 order exactly, and recomputing it from a tax rate that has since changed will not do that.

Distributing a discount without losing a cent

Cart-level discounts are the other reliable source of stray cents, because a percentage of a cart rarely divides evenly across lines. Ten dollars off a hundred dollar cart with three lines of $33.33, $33.33, and $33.34 gives each line an exact discount of $3.333, $3.333, and $3.334. Round each one down and you have distributed $9.99. The last cent has to go somewhere.

Largest remainder allocation handles it. Floor every share to the minor unit, add up what you distributed, and hand the residual cents out one at a time to the lines with the largest fractional remainders until the discount is fully allocated. It is fifteen lines of code, and it guarantees the distributed amount equals the requested discount.

function allocate(total, weights) {
  const sum = weights.reduce((a, b) => a + b, 0);
  const exact = weights.map(w => (w * total) / sum);
  const base = exact.map(v => Math.floor(v));
  let residual = total - base.reduce((a, b) => a + b, 0);
  const order = exact
    .map((v, i) => ({ i, frac: v - Math.floor(v) }))
    .sort((a, b) => b.frac - a.frac);
  for (let k = 0; residual > 0; k++, residual--) base[order[k % order.length].i] += 1;
  return base;
}

Do the same for anything that splits a total: gift card redemption across a multi-line order, store credit, a shipping cost spread across shipments, a marketplace commission split. Each of them is a division that does not terminate, and each of them has to land on exactly the original amount.

Refunds are where rounding becomes a legal problem

Refunding $100 in three parts gives $33.33, $33.33, and $33.33, which is $99.99. The remaining cent cannot be refunded on its own if the payment method has a minimum, and it cannot be left sitting on the order as a balance, because finance will chase it at year end.

Refund from the stored line amounts rather than from a fresh division, and make the last refund of a fully refunded order the remainder instead of the calculated share. Keep a refunded_minor column, add to it inside a transaction, and refuse any refund that would exceed the captured amount. Then a partial refund after an exchange or a goodwill credit still lands on zero when the customer returns everything. This matters more than it used to, since tax authorities in several jurisdictions now expect the credit note to reverse the original tax exactly, not approximately.

The exchange rate is a fact with a timestamp

Multi-currency checkouts introduce a second number that gets recomputed when it should be recorded. A customer is charged in their presentment currency, and the merchant settles in theirs, and the two amounts stop agreeing the moment the rate moves.

Capture the rate, the presentment amount, and the converted settlement amount at authorization, and store all three on the order. When the payout arrives with a different number, the difference is an FX variance to be booked, not a bug to be fixed by recalculating. Reconciliation should compare the gateway's settled amount against the stored settlement amount. If it recalculates from today's rate, every foreign order will look wrong.

What the schema should look like

Use BIGINT for amounts, and carry the ISO currency code on every row that holds money. A column named total with no currency beside it is a future incident, especially in a system that ever runs more than one storefront.

Avoid float and double columns entirely, and be careful with fixed-precision decimal columns too. PostgreSQL's NUMERIC(12,2) rounds on insert, so a value that arrives as 19.999 is stored as 20.00 with no warning and no record that it changed. If the application is not already producing exact minor units, the column type is hiding the defect rather than preventing it. PostgreSQL's money type is worse for portable code because its formatting depends on the server's locale setting.

Add a check constraint that the parts add up: subtotal minus discount plus tax plus shipping equals total. It costs nothing at runtime and it catches the class of bug that otherwise surfaces in the finance team's spreadsheet three weeks later.

The tests that actually catch it

Property-based tests beat example-based tests here, because the failures live in the corners of the input space. Generate random carts, run them through pricing, and assert two invariants: the line amounts sum to the subtotal, and the subtotal plus tax plus shipping minus discount equals the total. Ten thousand cases find the rounding paths that a hand-written fixture never touches.

Add a refund test that refunds an order one line at a time and asserts the refunded total reaches exactly the captured amount. Add a golden-file test that renders an invoice and compares it to a stored snapshot, so a change in rounding behaviour breaks a test instead of a customer's trust. Then add a lint rule or a code review checklist item that no float or double appears in a money path, because the arithmetic is only exact if nothing in the chain converts it back.

One habit covers most of it: decide the exact integer amount at the moment of sale, store it with its currency, and let everything downstream read that number instead of working it out again. The cent stops going missing once nobody recalculates it.

Send Us a Message