Handle money without rounding errors in JavaScript
Intermediate · 4 min read
Money looks like the easiest data there is: a price, a total, a change amount. Yet adding three ordinary prices in JavaScript can give a total that is very slightly wrong, and a very slightly wrong total is enough to break a "free delivery over ₦10" rule at checkout.
In this tutorial you will total a small basket two ways: once in naira with decimals, and once in kobo as whole numbers. One naira is 100 kobo, the same way one dollar is 100 cents. You will see exactly where the decimal version goes wrong and why the kobo version can't. You need to know what an array is and how map and reduce work on one.
Why decimal money drifts
JavaScript stores numbers in binary. Whole numbers are stored exactly, but most decimals, like 0.1 or 8.7, are stored as the nearest binary value, a tiny bit above or below. Usually you never notice. Add a few of them and the tiny errors can pile up:
console.log(8.7 + 0.1 + 1.2); // 9.999999999999998
That should be exactly 10. It is off by less than a millionth of a kobo, but 9.999999999999998 >= 10 is false, and a program makes decisions with comparisons like that.
The fix: count the smallest unit
Whole numbers don't have this problem. JavaScript stores every whole number exactly up to about 9 million billion, which is about 90 trillion naira counted in kobo. So the usual rule for money is: store the amount as a whole number of the smallest unit (kobo, cents, pence), do all the math on those whole numbers, and only divide by 100 when you show the amount to a person.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
63 Hold money in kobo, not naira
fairTotal a small basket twice: once in naira with decimals, once in kobo as integers. Also exercise 8, which sums a shopping list; the angle here is the unit the money is stored in.
Stuck? Three hints, smallest first
- 1. A price of ₦4.35 is 435 kobo. Store the integer, divide only when you display.
- 2.
Math.round(naira * 100), notMath.trunc— find out why with 4.35. - 3. Integers are exact up to 2⁵³, which is about 90 trillion naira in kobo. That is enough.
Step 1: total the basket in naira
Start the way most people would, with decimal prices:
const basketNaira = [8.7, 0.1, 1.2];
const totalNaira = basketNaira.reduce((a, b) => a + b, 0);
console.log(totalNaira); // 9.999999999999998
console.log(totalNaira >= 10); // false
console.log(totalNaira.toFixed(2)); // 10.00
reduce adds the prices one by one, starting from 0. The total is a hair under 10, so the free-delivery check says no. The worst part is the last line: toFixed(2) rounds to two decimals for display, so the receipt shows 10.00. The customer sees ten naira and is still refused. Nobody can reproduce a bug like that by reading the receipt.
Step 2: convert each price to kobo
Multiply by 100 to turn naira into kobo. The multiplication can land just off a whole number, so round it:
const toKobo = (naira) => Math.round(naira * 100);
console.log(8.7 * 100); // 869.9999999999999
console.log(toKobo(8.7)); // 870
console.log([8.7, 0.1, 1.2].map(toKobo)); // [ 870, 10, 120 ]
map runs toKobo on every price and gives you a new array. Every value in it is now an exact whole number.
Step 3: why Math.round and not Math.trunc
Math.trunc cuts off everything after the decimal point. It looks like it does the same job here. Try it on ₦4.35:
console.log(4.35 * 100); // 434.99999999999994
console.log(Math.trunc(4.35 * 100)); // 434
console.log(Math.round(4.35 * 100)); // 435
4.35 is stored slightly low, so times 100 lands just under 435. Cutting off the decimals throws away a whole kobo. Rounding goes to the nearest whole number, which is the right one. Convert once, with Math.round, on the way in.
Step 4: add in kobo and show in naira
Now add the kobo prices and divide by 100 only for display:
const toKobo = (naira) => Math.round(naira * 100);
const showNaira = (kobo) => (kobo / 100).toFixed(2);
const basketKobo = [8.7, 0.1, 1.2].map(toKobo);
const totalKobo = basketKobo.reduce((a, b) => a + b, 0);
console.log(totalKobo); // 1000
console.log(showNaira(totalKobo)); // 10.00
console.log(totalKobo >= 1000); // true
Adding whole numbers is exact, so the total is exactly 1000 kobo, and the free-delivery rule (now written as "at least 1000 kobo") agrees with the receipt. showNaira gives back text, '10.00', which is fine because it is only for the screen.
The full solution
The answer panel totals the same basket both ways, prints both totals, shows the refused free-delivery check and the kobo lost to Math.trunc. Its checks cover the conversion of ₦4.35, both totals and the formatted output. Press Run to see the output.
const toKobo = (naira) => Math.round(naira * 100);
const showNaira = (kobo) => (kobo / 100).toFixed(2);
const basketNaira = [8.7, 0.1, 1.2]; // should come to exactly 10 naira
const basketKobo = basketNaira.map(toKobo);
const totalNaira = basketNaira.reduce((a, b) => a + b, 0);
const totalKobo = basketKobo.reduce((a, b) => a + b, 0);
console.log('prices in naira ->', basketNaira);
console.log('prices in kobo ->', basketKobo);
console.log('total in naira ->', totalNaira, '<- look closely');
console.log('total in kobo ->', totalKobo, '=', showNaira(totalKobo));
console.log('free delivery over 10 naira?', totalNaira >= 10, '<- the customer disagrees');
console.log('trunc instead of round ->', Math.trunc(4.35 * 100), '<- a kobo lost');
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('4.35 naira is 435 kobo', toKobo(4.35), 435);
test('because 4.35 * 100 is not exactly 435', 4.35 * 100 === 435, false);
test('so truncating loses a kobo', Math.trunc(4.35 * 100), 434);
test('the naira total misses ten naira by a hair', totalNaira === 10, false);
test('so a "spend over 10" rule refuses a basket that qualifies', totalNaira >= 10, false);
test('and printing it hides the problem completely', totalNaira.toFixed(2), '10.00');
test('the kobo total is exact', totalKobo, 1000);
test('and formats back cleanly', showNaira(totalKobo), '10.00');
The fifth assertion is the bug in its natural habitat. ₦8.70 + ₦0.10 + ₦1.20 is ten naira, but in floating point it comes to 9.999999999999998, so the free-delivery threshold rejects a basket that clearly qualifies — and the receipt still prints 10.00, so the report and the behaviour disagree and nobody can reproduce it.
Math.trunc(4.35 * 100) giving 434 is the same flaw at the boundary: 4.35 is stored slightly low, so multiplying by 100 lands just under 435. Convert once with Math.round on the way in, do all arithmetic in kobo, divide once on the way out. Every currency has a minor unit for this reason, and it is why payment APIs take integer amounts.
Common mistakes
- Doing the math in naira and rounding at the end. The display looks right, but comparisons made before the rounding still see the wrong number.
- Using
Math.truncorMath.floorto convert. Values stored slightly low lose a kobo. UseMath.round. - Doing math on the
toFixedresult.toFixedgives text, not a number. Keep the kobo number for math and format it last.
Try it yourself
- Add a fourth item at ₦4.35 to the basket and check that the kobo total is 1435.
- Write
qualifiesForDelivery(totalKobo)that returnstruefrom 1000 kobo upwards, and test it with 999 and 1000. - Total
[0.1, 0.2]in naira and in kobo, and print both. Compare with the0.1 + 0.2result from the float lessons.