Storing money as Float: why the invoice is a cent off the quote
A complaint came in about a quoting system: the amount shown to the customer and the amount on the invoice were sometimes one cent apart. Not always — only at certain figures.
Why it happens
Binary floating point cannot hold decimal fractions exactly. 0.1 + 0.2 producing 0.30000000000000004 is the familiar example. One operation hides it. But a quote total runs this chain:
base price
→ subtract discount
→ add optional services
→ apply VAT
→ total
A small drift accumulates at each step. Then the same chain runs again on the invoicing side, perhaps in a slightly different order, and the two results disagree.
The real problem was having no single place to ask
Something worse was going on in our case: the discount logic lived in three places — the admin preview, the public quote page, and invoice generation — and the three did not agree. Entering a 10% discount showed 9,000 on the admin's screen while the customer was shown, and charged, 10,000.
That is not a rounding bug, it is an architectural one, and it has exactly one fix: a single module that answers every question about money.
export function calculateOfferTotals(
offer: OfferPricingInput,
optionalServices: OptionalServiceInput[] = []
): OfferTotals
Everything that displays a price, charges it, or invoices it calls this. They cannot diverge again.
Round to the cent at every step
If you are staying on Float — migrating an existing schema is not always possible — round each intermediate value before it feeds the next:
function toCents(value) {
return Math.round((Number.isFinite(value) ? value : 0) * 100) / 100;
}
The Number.isFinite guard matters: one bad value out of the database produces NaN, and that NaN propagates all the way to an invoice reading NaN. Falling back to zero at least leaves a visible error.
Test the specific numbers
These bugs only appear at particular figures, so the tests have to be concrete:
it("keeps the totals to the cent", () => {
const t = calculateOfferTotals({
price: 3333.33, discountType: "PERCENT", discountValue: 3
});
expect(t.discountAmount).toBe(100);
expect(t.netPrice).toBe(3233.33);
expect(t.taxAmount).toBe(646.67);
expect(t.total).toBe(3880);
});
Worth covering too: a 100% discount must not go negative, a fixed discount must not exceed the price, and a negative service price must not reduce the total.
The right answer: integer cents
If you are designing a new schema, store money as an integer number of cents. 3,880.00 is 388000 in the database. Floating point never enters the picture, all arithmetic is exact, and you divide by a hundred only at the display layer.
The cost: on an existing system this is a data migration, and it is money you are migrating — work that has to be done carefully. But only once.