Munchable Premium costs £10 a month. That figure exists once, as an integer:
export const PREMIUM_PRICE = {
currency: 'gbp',
unitAmount: 1000,
interval: 'month',
productName: 'Munchable Premium',
} as const;
Every other price on the site and in the app is derived from those 1000 pence. There are 24 currencies in the table and 58 country codes mapped onto them, so a visitor sees one fixed local figure rather than a conversion: £10, or €12.99, or 4500 Ft, and that same figure is what the Checkout Session is created for. The price does not move between the page and the card.
Deriving 24 prices from one number is arithmetic. The part that took real care is that money is not uniformly counted in hundredths, and the three systems involved do not agree about which currencies are the exceptions.
Who disagrees with whom
Three sources of truth here. Our own table. Intl.NumberFormat, which decides how a number is written. And Stripe, which decides what an integer in unit_amount means.
For 21 of our 24 currencies they all agree: two decimal places, unit_amount in hundredths, done. The other three:
Intl digits Stripe reads unit_amount as £10 displays as unit_amount sent
jpy 0 whole yen ¥2,300 2300
isk 0 hundredths, divisible by 100 1.800 kr. 180000
huf 0 hundredths, divisible by 100 4500 Ft 450000
Yen is the easy one: written without decimals, charged without decimals, and the two conventions line up. Icelandic krónur and Hungarian forint are written without decimals and charged in hundredths anyway, which Stripe then insists must come out to a whole number of major units. So a 4,500 forint price goes over the wire as 450000.
Note what is at stake in that column. If you treat forint like yen and send 4500, Stripe charges 45 Ft and you have given the product away. If you treat yen like forint and send 230000, you charge ¥230,000 for a £10 subscription. Neither throws. Both are valid requests for an amount of money, and the only thing that notices is a customer or an accountant, later.
Reading the digits instead of knowing them
The first rule I settled on is that nothing in the module is allowed to assume two:
/**
* Read from Intl rather than assumed to be 2, because zero-decimal currencies
* exist in this table: ISK, HUF and JPY are all written without decimals in
* their own locales. Quoting a price of 2999 yen as "¥29.99" would be wrong by
* two orders of magnitude, and silently so.
*/
export function minorUnitDigits(currency: DisplayCurrency): number {
const { code, locale } = CURRENCIES[currency];
return (
new Intl.NumberFormat(locale, { style: 'currency', currency: code }).resolvedOptions()
.maximumFractionDigits ?? 2
);
}
Six lines, and it is the only place in the codebase that knows how many digits a currency has. Everything that scales between major and minor units calls it. The alternative, a second hand-written list of zero-decimal currencies, means two lists that can disagree, and the day they disagree is the day somebody is charged wrong.
That function is what makes the display side honest. It is also not sufficient for the charging side, because Intl describes typography and Stripe describes an API, and the forint case is exactly where those two part company.
The function allowed to know about Stripe
export function checkoutPrice(
pence: number,
currency: DisplayCurrency,
): { currency: DisplayCurrency; unitAmount: number } {
const { code } = CURRENCIES[currency];
const displayed = priceIn(pence, currency);
const stripeDigits = STRIPE_ZERO_DECIMAL.has(code) ? 0 : 2;
const unitAmount = Math.round(displayed * Math.pow(10, stripeDigits - minorUnitDigits(currency)));
if (STRIPE_DIVISIBLE_BY_100.has(code) && unitAmount % 100 !== 0) {
throw new Error(`checkoutPrice: ${code} amounts must divide by 100, got ${unitAmount}`);
}
return { currency, unitAmount };
}
The whole of the disagreement is that one exponent: stripeDigits - minorUnitDigits(currency). For euros it is 2 minus 2, so the amount passes through. For yen it is 0 minus 0, so it passes through. For forint it is 2 minus 0, so the displayed figure is multiplied by a hundred. One subtraction that reads as noise unless you know both systems, which is why there is a nine-line comment above it in the real file.
Two things about the tables it reads. They hold Stripe's complete lists, not only the currencies we sell in:
export const STRIPE_ZERO_DECIMAL: ReadonlySet<string> = new Set([
'BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA',
'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF',
]);
export const STRIPE_DIVISIBLE_BY_100: ReadonlySet<string> = new Set([
'HUF', 'ISK', 'TWD', 'UGX',
]);
Fifteen entries of which we use one, four of which we use two. Carrying the twelve we do not sell in looks like dead data and is the opposite: adding Korean won to the price table a year from now is one line in one place, and the special case is already handled. A table trimmed to current needs is a trap laid for the next person who adds a row.
And the throw is deliberately a throw. The % 100 check cannot fire today, because every forint and krónur price is a whole number of major units multiplied by a hundred. It exists for the change that makes it possible, and the reasoning is in the comment on the zero-decimal set:
* Sending 1299 for a ¥1,299 price would charge
* ¥1,299 correctly, but sending a hundredths figure would charge a hundred
* times too much, so this is the kind of mistake that has to be impossible
* rather than caught.
A failed checkout is an annoyed customer. A hundredfold charge is a chargeback, a refund, an apology and a reputation. When those are the two options, crash.
Rounding, which is also two shapes
The other place currency conventions leak in is the round-up. Each local price is rounded up, because we settle in GBP and Stripe takes a conversion percentage on the way back, so £10 of list price has to still be about £10 of revenue. But "round up to a price-looking number" means different things in different places:
function ceilToRetail(amount: number, digits: number): number {
const EPSILON = 1e-9;
if (digits === 0) {
// 100 above a thousand, 10 above a hundred, whole units below that.
const step = amount >= 1000 ? 100 : amount >= 100 ? 10 : 1;
return Math.ceil((amount - EPSILON) / step) * step;
}
const step = 1 - Math.pow(10, -digits); // 0.99 for 2dp, 0.9 for 1dp
return Math.ceil(amount - step - EPSILON) + step;
}
Two-decimal currencies go to the next .99, which is why £10 is €12.99. Zero-decimal currencies cannot do that, and the naive fix (round to the next whole unit) produces ¥2,246, which reads as the output of a conversion rather than as a price. So the step scales with the size of the number: yen lands on ¥2,300 and forint on 4,500 Ft, which is how prices are written on a shelf in Tokyo and Budapest.
The epsilon is there because Math.ceil on a float that is already exactly on a boundary will sometimes push it a whole step up, and a whole step in forint is a hundred.
One more guard in the same family, which is my favourite line in the file for how small the bug it prevents is:
if (pence === 0) return 0;
Without it the round-up turns the free tier's £0 into €0.99, and the plan whose entire selling point is that it has no price acquires one. You can see the result of that line on munchable.app/#pricing, where the free tier reads as a plain zero in whatever currency you are served and the paid one has the .99 on it.
The test that would catch all of this
The unit tests for the three odd currencies are the obvious ones, and they are not the valuable ones. This is:
// The test that catches a hundredfold unit error anywhere in the table: every
// amount, read back as Stripe reads it, has to be worth roughly £10.
test('every currency charges about what the pound price is worth', () => {
for (const currency of DISPLAY_CURRENCIES) {
const { code } = CURRENCIES[currency];
const { unitAmount } = checkoutPrice(PREMIUM_PRICE.unitAmount, currency);
const major = unitAmount / (STRIPE_ZERO_DECIMAL.has(code) ? 1 : 100);
const pounds = major / CURRENCIES[currency].rate;
assert.ok(pounds >= 10, `${currency} charges only £${pounds.toFixed(2)}`);
assert.ok(pounds <= 12, `${currency} charges £${pounds.toFixed(2)}`);
}
});
It takes the integer we would hand Stripe, divides by what Stripe thinks that integer means, converts back to pounds at the table's own rate, and asserts the answer is between £10 and £12. Twenty-four assertions, no expected values typed out, and a factor-of-a-hundred error anywhere in the pipeline fails it by two orders of magnitude rather than by a rounding step. The £12 ceiling catches the overcharge and the £10 floor catches the undercharge, and the band between them is the conversion buffer plus the round-up, so a new currency has to be wrong in a specific way to pass.
Its companion closes the loop back to the page:
test('the amount sent to Stripe is the price on the page', () => {
const cases: Array<[DisplayCurrency, number]> = [
['gbp', 1000],
['eur', 1299],
['sek', 13399],
['jpy', 2300],
['huf', 450000],
];
...
assert.equal(
formatMinorUnits(written, currency),
formatPrice(PREMIUM_PRICE.unitAmount, currency),
currency,
);
Five cases, one per shape of currency: pounds, ordinary hundredths, a krona written with a decimal comma, yen in whole units, and forint sent as hundredths of a currency that has none. It takes the unit_amount, writes it back out as a human-readable price, and asserts that string equals what the pricing table on the website prints. That is the only promise a customer cares about, written as an assertion.
And one line of hygiene that is worth stealing on sight:
test('Stripe\'s zero-decimal and divisible-by-100 lists are disjoint', () => {
for (const code of STRIPE_DIVISIBLE_BY_100) {
assert.equal(STRIPE_ZERO_DECIMAL.has(code), false, code);
}
});
Two hand-copied lists from somebody else's documentation feed one branch. If a code ever appears in both, that branch is a coin toss between whole units and hundredths, and it will be read as working because it works for the currency you tested.
What I would tell anyone starting this
Three things, and none of them are about Stripe specifically.
Never let the number 2 appear as a hardcoded exponent anywhere near money. Read it, from one function, and let everything scale through that.
Keep the vendor's full exception list, not the subset you currently need. The cost is a dozen strings, and the thing it buys is that adding a currency cannot silently miss its case.
And write the one invariant test that reads the value back the way the other system will read it. Every typed expectation in a money test is a number you can get wrong in both places at once. "Convert it back and check it is still worth ten pounds" is a claim neither side can satisfy by agreeing with your mistake.
If you want to see what the table outputs, munchable.app/#pricing prints whichever of the 24 your request resolves to, and it is the same figure the checkout is created for, which was the whole point of doing it this way.
Top comments (1)
The silent part is the killer: no exception, just a hundredfold charge. Your round-trip test is the right gate — the 30-second standalone version of it, runnable in node with no repo, is this:
It fails loudly on the first currency where display and charge disagree. Drop your own
checkoutPricein place of the Intl math and loop it over all 24 — then the next zero-decimal or three-decimal currency breaks the build instead of a charge.