CodeOrigin All articles
Software Engineering

The Cent That Wasn't There: A Money Model for Invoices That Must Add Up

CodeOrigin
The Cent That Wasn't There: A Money Model for Invoices That Must Add Up

A customer opens an invoice and finds a total that is one cent higher than the sum of its lines. No one typed the extra cent. No tax rule asked for it. It appeared because a decimal amount passed through a binary floating-point number and came out the other side slightly changed. The bug is not exotic; it is the predictable result of asking a representation designed for approximate scientific values to behave like a cash ledger.

The fix is not a single library call. It is a small model, applied consistently from the first calculation to the database constraint to the API response. The model begins with a question that sounds trivial and is not: what unit are we counting?

Start With the Unit, Not the Number

Money is not a real number. It is a count of indivisible units in a named currency. In the United States, the unit is the cent for USD, and an invoice amount of $19.99 is 1,999 cents. That sentence is the foundation. Once the unit is explicit, addition becomes exact, comparison becomes exact, and storage becomes exact.

Binary floating point fails here because most decimal fractions have no finite binary expansion. The familiar 0.1 + 0.2 example is not a party trick; it is the same mechanism that makes 19.99 * 1.0825 produce a value that is not quite the tax amount a human would compute. Rounding that value at the end can hide the error, but it cannot tell you which rounding rule was intended, where it was applied, or why two services disagree.

Use integer minor units for amounts. Use a decimal or numeric type for rates, percentages, and exchange ratios. Do not use a floating-point type for either.

Integers in Minor Units, Guarded by the Type System

A raw integer is an improvement, but it is still easy to pass a count of items where an amount was expected. A small branded type in TypeScript makes the unit visible at call sites without imposing a runtime tax.

type CurrencyCode = 'USD';

type Money = { readonly minor: bigint; readonly currency: CurrencyCode; };

function money(minor: bigint, currency: CurrencyCode): Money { return { minor, currency }; }

function add(a: Money, b: Money): Money { if (a.currency !== b.currency) { throw new Error('Cannot add different currencies'); } return money(a.minor + b.minor, a.currency); }

bigint avoids the safe-integer ceiling that ordinary JavaScript numbers eventually hit, and it forces explicit conversion at the formatting boundary. Formatting is where minor units become a human string, and it is the only place where division by 100 belongs.

For display, Intl.NumberFormat is appropriate after converting to a number for typical invoice sizes. For very large values, format from the integer digits directly rather than accepting silent precision loss.

Rounding Is a Policy, Not a Side Effect

Every tax calculation, discount, and proration eventually produces a fractional minor unit. The question is not whether to round, but where and by which rule. Half-up rounding is common in US billing contexts, but it is not universal, and it is not the same as banker's rounding. The policy must be named, stored, and tested.

A tax rate stored as basis points or as a PostgreSQL numeric can be applied with integer arithmetic:

function taxHalfUp(subtotalMinor: bigint, rateBps: bigint): bigint { return (subtotalMinor * rateBps + 5000n) / 10000n; }

The + 5000n implements half-up for non-negative values at basis-point precision. Refunds and credit notes require a deliberate decision about negative amounts. Half-up toward positive infinity is not the same as half-away-from-zero. Document the choice and keep it consistent across invoice creation, credit issuance, and reporting.

Line-level rounding and invoice-level rounding produce different totals. If tax is calculated per line for jurisdictional reasons, sum the rounded line taxes; do not recalculate tax on the invoice subtotal and expect the same answer. The invoice must record which policy produced its numbers.

Allocation: When One Total Meets Many Lines

Discounts create a related problem. A $10 discount across three lines cannot be divided into equal cents. Allocating 333, 333, and 334 cents is arbitrary unless the rule is explicit. Largest-remainder allocation is a practical default: compute the floor for each line, then distribute the remaining cents to the lines with the largest fractional remainders, breaking ties by line order or identifier.

The invariant is simple and testable: the allocated amounts must sum exactly to the original total, and every line must remain non-negative where the business rule requires it. An allocation function that returns amounts which almost sum to the total has not solved the problem; it has moved it downstream.

Refunds Are Entries, Not Reversals

A refund should not mutate the original charge into a smaller number. It should append a new entry with its own identifier, timestamp, reason, and amount. The original invoice remains a historical fact. The ledger remains additive.

This is where money arithmetic meets auditability. A refund of $7.43 against a $19.99 charge is a negative entry of 743 cents, not an edit that changes 1,999 to 1,256. If tax was collected, the refund should reference the original tax treatment and the policy used to prorate it. Idempotency keys belong on the API request so a retried refund cannot become two refunds.

A PostgreSQL Schema That Refuses Ambiguity

Store amounts as bigint minor units with an explicit currency column. Store rates as numeric with a declared scale. Add check constraints for the relationships the application depends on.

CREATE TABLE invoices ( id uuid PRIMARY KEY, currency char(3) NOT NULL CHECK (currency = 'USD'), subtotal_minor bigint NOT NULL, tax_minor bigint NOT NULL, total_minor bigint NOT NULL, rounding_policy text NOT NULL, CHECK (total_minor = subtotal_minor + tax_minor) );

CREATE TABLE ledger_entries ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, invoice_id uuid NOT NULL REFERENCES invoices(id), currency char(3) NOT NULL, amount_minor bigint NOT NULL, kind text NOT NULL CHECK (kind IN ('charge', 'refund', 'tax', 'adjustment')), created_at timestamptz NOT NULL DEFAULT now() );

The constraint does not replace application logic, but it catches the class of defect where a service writes a total that its own parts contradict. That failure should be loud at write time, not discovered by a customer or a month-end reconciliation.

The API Contract Is Part of the Arithmetic

An API that returns 19.99 as a JSON number invites every client to guess the type. Return minor units as integers, name the currency explicitly, and include the rounding policy when the response represents a calculated total.

interface InvoiceResponse { currency: 'USD'; subtotalMinor: number; taxMinor: number; totalMinor: number; roundingPolicy: 'half_up_line'; }

For typical US invoice amounts, JSON integers are safe within the IEEE 754 safe-integer range. For larger values, return minor units as strings and document the boundary. The important point is that the contract states the unit. A field called amount with no unit is not a money contract; it is an invitation to a future dispute.

Tests That Assert the Ledger, Not the Formatting

The highest-value tests are invariants: every invoice total equals the sum of its ledger entries; every refund references an original charge; every allocation sums to its source total; every tax calculation uses the declared rounding policy. Formatting tests are useful, but they are secondary. A beautifully formatted invoice that does not reconcile is still wrong.

Money arithmetic survives when the unit is explicit, the rounding policy is named, the allocation rule is total-preserving, and the ledger is append-only. Those are not accounting formalities. They are the first principles that keep a checkout system from inventing a cent that was never there.

All Articles

Related Articles

Two O’Clock, Twice: A First-Principles Design for Civil-Time Scheduling

Two O’Clock, Twice: A First-Principles Design for Civil-Time Scheduling

The Build That Always Compiles the Same: Tracing Nondeterminism to Its Sources

The Build That Always Compiles the Same: Tracing Nondeterminism to Its Sources

When Histories Diverge: Building a Three-Way Merge From the Diff Up

When Histories Diverge: Building a Three-Way Merge From the Diff Up