Shipmind Labs

Multiplying money by a rate needs a rounding mode, or an error

· 10 min read

A percentage of an amount is almost never a whole number of minor units. Nineteen percent of 99.99 EUR works out to 1899.81 cents, the ledger has no room for the 0.81, and the direction that fraction travels is a business rule rather than a property of arithmetic. A library that picks a direction silently is how an invoice total ends up a cent away from the sum of its own lines, in a way nobody can spot by reading either number.

We have hit this in every payment, lending and marketplace system we have built, and it is the rule we encoded in amountfield, the money input we maintain at https://github.com/shipmindlabs/amountfield. multiply scales a Money by a rate without ever forming a float. When the product is a whole number of minor units it comes back and nothing is asked of you. When it is not, you get an error until you name where the fraction goes.

The constraint: the arithmetic cannot know#

An amount in this library is three things that travel together, and the first of them is a count rather than a measurement:

typescript
type Money = {
  readonly minor: bigint;    // 1234
  readonly currency: string; // "EUR"
  readonly exponent: number; // 2
};

Because minor is a whole number of the currency's smallest unit, every rate that does not divide evenly leaves a leftover that has to be resolved before the value exists at all. The resolution does not follow from the inputs. A fee quoted to a customer is usually rounded down, because charging a cent more than the quote is the expensive kind of wrong. A long column of interest accruals wants half-even, so that a thousand ties do not drift upward together. A statutory minimum wants ceil. Those are different answers to the same expression, and the expression holds nothing that tells them apart.

So there are three tempting defaults and all three are unsafe. Half-up is the most common one and it drifts on long columns. Truncation loses money in one direction forever. Doing the work in number destroys the question before anyone can ask it, because the product is no longer the number anyone wrote down.

The rate has to be exact before the leftover can be discussed#

You cannot decide where a fraction goes until you know the fraction, which means the rate itself cannot be approximate. 0.19 as a binary double is not nineteen hundredths. So a rate is first read into a pair of integers:

typescript
type Exact = { readonly n: bigint; readonly d: bigint };

function ratioOf(ratio: Ratio): Exact {
  if (typeof ratio === "object") {
    const top = exactly(ratio.numerator);
    const bottom = exactly(ratio.denominator);
    if (bottom.n === 0n) throw new RangeError("a ratio with a denominator of zero is not a ratio");
    return { n: top.n * bottom.d, d: top.d * bottom.n };
  }
  return exactly(ratio);
}

function exactly(value: bigint | number | string): Exact {
  if (typeof value === "bigint") return { n: value, d: 1n };
  if (typeof value === "number") {
    if (!Number.isSafeInteger(value)) throw new InexactRatio(value);
    return { n: BigInt(value), d: 1n };
  }

  const text = value.trim();
  if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(text)) throw new InexactRatio(value);
  const digits = text.replace(/^[+-]/, "");
  const [whole = "", fraction = ""] = digits.split(".");
  const n = BigInt((whole || "0") + fraction);
  return { n: text.startsWith("-") ? -n : n, d: 10n ** BigInt(fraction.length) };
}

A bigint or a whole number gets a denominator of 1n. A string has to look like a plain signed decimal, and it becomes its digits over ten to the power of the fraction length, so "0.19" is literally 19n/100n and not a value sitting near it. A numerator and denominator pair is assembled out of two such readings.

The interesting branch is the refusal. A number that fails Number.isSafeInteger, and 0.1 fails it, throws InexactRatio, whose message tells you to write the ratio as text or as a numerator and a denominator. This is not about purity. It is that 0.1 in source is a request the runtime cannot honour, and accepting it would mean rounding a product that was already wrong.

typescript
assert.throws(() => multiply(amount("1.00"), 0.1), InexactRatio);
assert.throws(() => multiply(amount("1.00"), "nineteen percent"), InexactRatio);
assert.throws(() => multiply(amount("1.00"), { numerator: 1, denominator: 0 }), RangeError);
// The exact forms of the same ratio agree.
assert.equal(multiply(cents(1000n), "0.1").minor, 100n);
assert.equal(multiply(cents(1000n), { numerator: 1, denominator: 10 }).minor, 100n);

That last pair is the property that makes the design liveable: a rate written as a decimal string and the same rate written as two integers give you the same bigint. Your configuration can stay in whatever shape it already has.

An exact product asks nothing#

multiply computes money.minor times n and tests the remainder against d. If the remainder is zero, the rounding argument never gets consulted, and it does not need to be, because there is no fraction to place.

typescript
assert.equal(multiply(amount("12.50"), 3).minor, 3750n);
assert.equal(multiply(amount("12.50"), 3n).minor, 3750n);
assert.equal(multiply(amount("1.00"), "0.5").minor, 50n);
assert.equal(multiply(amount("1.00"), { numerator: 1, denominator: 4 }).minor, 25n);
assert.equal(multiply(amount("1.00"), "-0.5").minor, -50n);

This is what keeps the rule from turning into noise. Quantity times unit price is the most common multiplication in any commerce system and it is exact by construction, so it stays a two-argument call. The third argument shows up where a fraction can genuinely occur, which is also where a reviewer should be reading closely.

When the product is not whole, a missing mode is InexactAmount, and a mode that is not in the list is a RangeError:

typescript
assert.throws(() => multiply(amount("1.00"), "0.075"), InexactAmount);
assert.throws(() => multiply(amount("99.99"), "0.19"), InexactAmount);
assert.equal(multiply(amount("1.00"), "0.075", "half-even").minor, 8n);
assert.throws(() => multiply(amount("1.00"), "0.075", "nearest" as Rounding), RangeError);

Two refusals, two different mistakes. The first one is a decision nobody made; its message lists the available roundings and points you at allocate, because the caller who reaches it is often asking the wrong question entirely. The second one is a typo, and a typo in a rounding mode must not degrade into a default.

Naming where the fraction goes#

The placement itself is small, and worth reading in full, because every branch of it is a sentence somebody in finance has said out loud:

typescript
function divide(numerator: bigint, denominator: bigint, rounding: Rounding): bigint {
  const n = denominator < 0n ? -numerator : numerator;
  const d = denominator < 0n ? -denominator : denominator;
  const quotient = n / d; // truncated toward zero
  const rest = n % d; // carries the sign of the dividend
  if (rest === 0n) return quotient;

  const negative = rest < 0n;
  const away = negative ? quotient - 1n : quotient + 1n;
  const twice = (negative ? -rest : rest) * 2n;

  if (rounding === "down") return quotient;
  if (rounding === "up") return away;
  if (rounding === "floor") return negative ? away : quotient;
  if (rounding === "ceil") return negative ? quotient : away;
  if (rounding === "half-up") return twice >= d ? away : quotient;
  if (twice !== d) return twice > d ? away : quotient;
  // half-even: an exact tie goes to the even unit, so a long column of them
  // does not drift upwards.
  return quotient % 2n === 0n ? quotient : away;
}

The sign normalisation on the first two lines means a rate written with a negative denominator behaves like the same rate written with a negative numerator, instead of quietly inverting the direction of rounding. Everything after it works on the magnitude, with away standing for one unit further from zero.

The reason the mode has to be named at the call site, rather than configured once per application, shows up in a single table. Half of five cents, and half of minus five cents:

typescript
const expected: Record<string, [bigint, bigint]> = {
  down: [2n, -2n],
  up: [3n, -3n],
  floor: [2n, -3n],
  ceil: [3n, -2n],
  "half-up": [3n, -3n],
  "half-even": [2n, -2n],
};

down and floor agree on the positive amount and disagree on the negative one. A refund, a chargeback and a credit note are all negative amounts, so a policy you chose while looking only at charges will behave differently the first time money moves the other way. Making the mode an argument means the two cases can be written differently when they should be, and a reviewer can see which one was chosen. The result keeps the currency and exponent of the input, so a rate applied to a JPY amount with exponent 0 does not silently acquire decimals.

Splitting a total is a different question#

A large share of InexactAmount throws are not really about rounding. They are an attempt to split a total by multiplying it by fractions, which cannot conserve the total no matter which mode you name. That is why the message points you elsewhere:

typescript
assert.deepEqual(allocate(cents(5n), 3).map((part) => part.minor), [2n, 2n, 1n]);
assert.deepEqual(allocate(cents(100n), 3).map((part) => part.minor), [34n, 33n, 33n]);
assert.deepEqual(allocate(cents(5n), [3, 7]).map((part) => part.minor), [2n, 3n]);
assert.deepEqual(allocate(cents(-5n), 3).map((part) => part.minor), [-2n, -2n, -1n]);
// A weight of zero is a share of nothing, even while units are left over.
assert.deepEqual(allocate(cents(1n), [0, 1, 1]).map((part) => part.minor), [0n, 1n, 0n]);

allocate hands out the floor of each share and then distributes the leftover units by largest remainder, so nothing is lost and nothing is invented. It works on the magnitude and applies the sign afterwards, so a negative total is split the same way the positive one is, rather than by however truncation happened to fall. Three thirds of a cent come back as two, two and one, not as two cents total.

The distinction we hold to in review is simple: a rate applied to one amount is multiply and needs a policy, and one amount distributed over several recipients is allocate and needs a conservation guarantee.

What it costs to run#

One more argument at every call site that can produce a fraction. In the systems where this matters (tax lines, fee schedules, interest accrual, pro-rata investor returns, discounts) that is most of the money-touching multiplications, and all of them are places where a reviewer ought to be reading the rounding anyway. The cost and the benefit are the same thing here: multiply(line, taxRate, "half-up") is a line somebody can disagree with in a pull request, which an implicit default is not.

The second cost is that rates have to arrive in an exact shape. In practice we think this is less work, not more, because rates arrive from configuration and databases as strings and the usual first step is to parse them into a float. Keeping them as strings until multiply reads them removes a step. The integer arithmetic underneath is not where a request spends its time; the expensive part of a payment path is the network, not a bigint remainder.

The third cost is the honest one: existing code does not compile after this rule lands, because every inexact multiplication now needs a decision. That migration is the audit. Every site the compiler stops at is a place where the rounding used to be whatever the language happened to do.

We would rather fail a build than explain a one-cent discrepancy on a reconciliation call. An error at the call site is cheap and a drifting total is not, and for a decision nobody has made, the safe default is to refuse to make it.

Was this useful?

Building something similar?

or email hello@shipmindlabs.com