← Math
Math

Floating point and rounding

Is the billing export a cent over, or is that float noise?

Choose a representation and rounding rule that preserve the quantity being counted.

Outcome

Bound binary64 rounding error, recover whole cents, compare money in minor units and allocate a total without losing a unit.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

binary64 Also double
The floating-point format behind TypeScript numbers, Go float64, Rust f64 and C++ double: 53 significant bits, so most decimal fractions are stored approximately.
Minor unit
The smallest unit a currency is counted in, such as the cent. USD has 2 decimal digits of minor units, JPY 0 and KWD 3.
Rounding error
The difference between a real number and the nearest value a format can store. For a double near 30 it is at most a few times 10⁻¹⁵.
Rounding mode
The rule for choosing a whole number: down, up, toward zero, to nearest with halves up, away from zero or to even.
Largest-remainder allocation
Split a whole number of units by giving each part the whole part of its exact share, then the leftover units to the largest fractional remainders.

Why this matters

Payments, invoices, tax and quotas are counted in whole minor units, but code often carries them as doubles. Most of the time the error is invisible; then a floor turns 29 cents into 28, a tolerance hides a real cent, or a split loses one. Knowing how large the error can be tells you where rounding is safe and where integers are required.

This lesson assumes the Fundamentals floating-point picture: a binary64 value keeps 53 significant bits and stores the nearest value it can.

Where rounding enters a calculation

A binary64 value represents a finite binary fraction. A decimal input can fall between representable values, and arithmetic introduces further rounding. Displaying two decimal places changes the text you see; it does not make the stored calculation exact.

For money counted in whole cents, distinguish recovering an intended cent amount from rounding a genuine fraction of a cent. The first needs a justified conversion error bound; the second needs an allocation or rounding policy. A comparison tolerance answers a separate question: which differences the application agrees to accept.

01What a double stores

A double stores the nearest value it can

A nightly job checks a cloud billing export against its invoice and treats anything within 0.01 dollars as a match. This month three teams were each billed 3.33 on a 10.00 invoice. Decide what the job will report, what it should compare, and how to split the invoice so it adds up.

0.29 has no exact binary fraction, so a double stores 0.28999999999999998002…, about 2 × 10⁻¹⁷ below it. Predict what each line of this program prints.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const amount = 0.29; // dollars
const [a, b] = [0.1, 0.2];

console.log(amount * 100);
console.log(Math.floor(amount * 100), Math.round(amount * 100));
console.log(a + b === 0.3);
What does the first line print?

Every version prints 28 29 on the second line: floor falls to 28, rounding to nearest recovers 29. The third line is false: 0.1 + 0.2 is stored as 0.30000000000000004.

02Recover whole cents

Recover whole cents with a bound

Rounding to the nearest cent is safe when the float error is far below half a cent. Doubles near 10¹¹ are spaced about 1.5 × 10⁻⁵ apart, so any two-decimal amount below a billion dollars, multiplied by 100, lands within a few of those steps of its whole number of cents. Rounding recovers it; floor and truncation do not, because the stored value can sit just below.

For this lab, each amount has at most two decimal digits and magnitude below a billion dollars. Accounting for both parsing and multiplication gives an error below 0.00002 cents, far below 0.5 cents. This recovers an already-whole cent amount; it is not a policy for rounding a genuine fractional-cent charge.

After that conversion, keep cents as integers. With at most 1,000 export lines, the sum and invoice difference have magnitude below 10¹⁴ + 10¹¹ cents, within the exact integer range of all four lab languages.

03Compare in minor units

Compare in minor units, not with a float tolerance

Three line amounts of 3.33 against an invoice of 10.00, compared as doubles with a 0.01 tolerance. What does the job report?

04Preserve the total

Split a total so the parts add up

The invoice is split across teams by usage. Exact shares are fractions of a cent, and rounding each one separately can lose or gain cents: three equal shares of 1,000 round to 333 each, one cent short. Instead, give each team the whole part of its share, then hand the leftover cents to the largest fractional remainders, earlier teams first on ties.

100 cents split by usage 3 : 3 : 1
TeamExact shareWhole partRemainderShare
A42.857…420.85743
B42.857…420.85743
C14.286…140.28614
Why do the two leftover cents go to A and B rather than one to C?

Compute the whole parts and remainders with integer division: total × weight ÷ sum and total × weight mod sum. The lab limits an allocation to 0–1,000,000,000 cents and 1–100 teams, with whole weights from 0 to 1,000,000 and a positive weight sum. Products stay at or below 10¹⁵ and the sum at or below 10⁸. Integer remainders compare exactly, so ties are real ties.

05Choose the rounding mode

Choose the rounding mode on purpose

Where a value really lands on a half, such as a tax of exactly 2.5 cents, the rounding mode decides the result, and languages disagree about negative halves.

Math.round rounds halves toward +∞: Math.round(2.5) is 3 and Math.round(-2.5) is -2. There is no built-in round-half-to-even.

06Reconcile the invoice

Build the invoice reconciler

The reconciler needs one trustworthy conversion at the export boundary before it can distinguish float noise from a missing cent. Once the invoice agrees with its lines, allocating it by team usage introduces real fractions of a cent. Preserve the total while choosing which teams receive the leftovers; rounding each share independently no longer answers the accounting question.

In the frontend Currency display in Next.js and Svelte Optional

Display is the last rounding boundary. Intl.NumberFormat with style: "currency" knows each currency’s minor digits (2 for USD, 0 for JPY, 3 for KWD), and given a decimal string it formats that exact decimal. Build the string from integer minor units instead of dividing by 100, which hard-codes two digits and puts a float back on the path.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Format integer minor units without putting a float on the path.
export function formatMinor(units: bigint, currency: string, locale = "en-US") {
  const format = new Intl.NumberFormat(locale, { style: "currency", currency });
  const digits = BigInt(format.resolvedOptions().maximumFractionDigits ?? 2);
  const scale = 10n ** digits;
  const sign = units < 0n ? "-" : "";
  const abs = units < 0n ? -units : units;
  const fraction =
    digits > 0n ? "." + String(abs % scale).padStart(Number(digits), "0") : "";

  return format.format(`${sign}${abs / scale}${fraction}` as `${number}`); // exact decimal string
}

export function InvoiceTotal({ cents }: { cents: bigint }) {
  return <strong>{formatMinor(cents, "USD")}</strong>;
}

Check this idea later
Adding 0.1 ten times as doubles and comparing with 1.0 using ==. What is the result?
Split 10 cents across three equal teams so the total is preserved. What split?
Sources

The invoice and teams are a worked model. Values and rounding results were run on Node 22, Go 1.27, rustc 1.99 and clang 17.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.