Emmanuel Akinfulubi

JavaScriptMath

Split money proportionally in JavaScript

Advanced · 4 min read

Split ₦100.00 between three people. Each should get ₦33.333..., which isn't a real amount of money. If you round each share to ₦33.33, you hand out ₦99.99 and one kobo is left over. In a bank, an invoice system or a payroll run, a kobo that goes missing (or appears from nowhere) is a bug someone has to explain.

In this tutorial you will split money so that the shares always add back to the total exactly. You will store amounts as whole kobo, split a refund three ways, split an invoice in the ratio 3 : 5 : 7, and take 7.5% VAT out of a price without breaking the receipt. Along the way you will see why adding prices as decimals is a bug that only shows up some of the time. You need to know map, reduce and sort.

Why money goes in whole kobo

JavaScript numbers are stored in binary, and most decimal fractions, like 0.1, can't be stored exactly. Usually the tiny error is rounded away when the number is printed. Sometimes it isn't:

JavaScript

console.log(0.1 + 0.2 === 0.3);          // false
console.log(4500 + 0.1 + 0.2 === 4500.3); // true

The first sum misses, the second hits. That is the worrying part: the error comes and goes. The fix is to count in kobo, whole numbers, where additions are always exact. ₦53.75 becomes 5375.

The largest-remainder rule

Whole kobo don't solve division. 10000 kobo doesn't divide by 3. The largest-remainder rule says: round every share down, count how many kobo are left over, and give one extra kobo each to the shares that lost the most when you rounded down.

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

106 Splitting money so every kobo lands somewhere

hard

Refund ₦100.00 to three people and split a ₦9,999.99 invoice between three cost centres in the ratio 3 : 5 : 7, in integer kobo, so that the shares add back to the total exactly. Then pull 7.5% VAT out of a VAT-inclusive price and show what goes wrong if you round both halves of it. Along the way, find one basket of naira prices whose float total is exactly right and one whose is not.

Stuck? Three hints, smallest first
  1. 1. Round each share separately and the parts no longer add up to the whole; the shortfall is the leftover kobo.
  2. 2. Floor every share, count how many kobo are still unallocated, then hand them to the shares with the largest discarded fraction.
  3. 3. When splitting a price into net and VAT, round one part and make the other the remainder.

Step 1: helpers for kobo

Step 1

const toKobo = (amount) => Math.round(amount * 100);
const naira = (kobo) => '\u20a6' + (kobo / 100).toFixed(2);
console.log(toKobo(53.75), naira(5375)); // 5375 ₦53.75

toKobo multiplies by 100 and rounds, so a small float error like 4.35 * 100 = 434.99999999999994 still lands on a whole number. '\u20a6' is the naira sign, and toFixed(2) always shows two decimal places.

Step 2: one basket adds up, the next doesn't

Step 2

const basketA = [1250.75, 899.99, 45.5, 12345.67];
const basketB = [12000.05, 3450.15, 89.9];
console.log(basketA.reduce((a, b) => a + b, 0)); // 14541.91
console.log(basketB.reduce((a, b) => a + b, 0)); // 15540.099999999999
console.log(basketB.map(toKobo).reduce((a, b) => a + b, 0)); // 1554010

Both baskets are written the same way. The first total is exactly right and the second is not. A test that uses basket A passes, and the bug waits for basket B. Converting to kobo first gives 1554010, exactly ₦15,540.10.

Step 3: the wrong turn, round every share

Step 3

const roundEach = (total, parts) => new Array(parts).fill(Math.round(total / parts));
const naiveThirds = roundEach(10000, 3);
console.log(naiveThirds, naiveThirds.reduce((a, b) => a + b, 0)); // [ 3333, 3333, 3333 ] 9999

Each share is fair on its own, but together they add to 9999. One kobo has gone missing.

Step 4: the largest-remainder split

Step 4

function allocate(total, weights) {
  const weight = weights.reduce((a, b) => a + b, 0);
  const exact = weights.map((w) => (total * w) / weight);
  const shares = exact.map(Math.floor);
  const left = total - shares.reduce((a, b) => a + b, 0);
  const byFraction = exact
    .map((v, i) => ({ i, frac: v - Math.floor(v) }))
    .sort((a, b) => b.frac - a.frac || a.i - b.i);
  for (let k = 0; k < left; k++) shares[byFraction[k].i]++;
  return shares;
}
console.log(allocate(10000, [1, 1, 1])); // [ 3334, 3333, 3333 ]

Line by line:

  • weight is the total of the ratio, and exact is each share as a decimal, like 3333.33.
  • Math.floor rounds every share down, and left counts the kobo still to hand out.
  • byFraction lists the shares by how much each one lost when rounded down, biggest first. When two lost the same amount, a.i - b.i puts the earlier share first, so the result is always the same.
  • The loop gives one kobo to each of the first left shares.

Now all 10000 kobo are handed out. One person gets 3334. That is a choice your app has to be able to defend, but no money is lost.

Step 5: an invoice in the ratio 3 : 5 : 7

Step 5

const centres = allocate(999999, [3, 5, 7]);
console.log(centres, centres.reduce((a, b) => a + b, 0)); // [ 200000, 333333, 466666 ] 999999
console.log([3, 5, 7].map((w) => (999999 * w) / 15));      // [ 199999.8, 333333, 466666.2 ]

The exact shares are 199999.8, 333333 and 466666.2. Rounding all three down leaves 1 kobo, which goes to the first share because it lost 0.8, the most. Every share is within one kobo of its exact value, and the total is the invoice to the kobo.

Step 6: take VAT out of a price

A price that includes 7.5% VAT is the net price times 1.075. To split it back, round the net, then make the VAT whatever is left:

Step 6

const RATE = 0.075;
const netOf = (gross) => Math.round(gross / (1 + RATE));
const vatOf = (gross) => gross - netOf(gross);
console.log(naira(netOf(5375)), naira(vatOf(5375))); // ₦50.00 ₦3.75

Because the VAT is a subtraction, net plus VAT always equals the price.

Step 7: the wrong turn, round both halves

What if you work out the VAT from the net and round it too?

Step 7

const net7 = netOf(7);
console.log(net7, Math.round(net7 * RATE), net7 + Math.round(net7 * RATE)); // 7 1 8

A 7-kobo price has a net of 7 and a rounded VAT of 1, which adds up to 8. Across the first 10000 prices, 698 go wrong this way. That is a receipt whose lines don't add up to its total.

The full solution

The answer panel has toKobo, naira, allocate, the VAT helpers and both baskets, and counts every price from 1 to 10000 where rounding both halves breaks. Press Run to see the output.

The answer

const toKobo = (amount) => Math.round(amount * 100);
const naira = (kobo) => '₦' + (kobo / 100).toFixed(2);

// Hand out `total` kobo in the given ratio. Floor every share, then give the
// unallocated kobo to the shares with the largest discarded fraction, largest
// first. This is the largest-remainder rule, and it never invents or loses a kobo.
function allocate(total, weights) {
  const weight = weights.reduce((a, b) => a + b, 0);
  const exact = weights.map((w) => (total * w) / weight);
  const shares = exact.map(Math.floor);
  const left = total - shares.reduce((a, b) => a + b, 0);
  const byFraction = exact
    .map((v, i) => ({ i, frac: v - Math.floor(v) }))
    .sort((a, b) => b.frac - a.frac || a.i - b.i);
  for (let k = 0; k < left; k++) shares[byFraction[k].i]++;
  return shares;
}

// The wrong way: round every share independently and hope.
const roundEach = (total, parts) => new Array(parts).fill(Math.round(total / parts));

// Two baskets of naira prices, priced the same way. Only one of them adds up.
const basketA = [1250.75, 899.99, 45.5, 12345.67];
const basketB = [12000.05, 3450.15, 89.9];
const floatA = basketA.reduce((a, b) => a + b, 0);
const floatB = basketB.reduce((a, b) => a + b, 0);
const koboA = basketA.map(toKobo).reduce((a, b) => a + b, 0);
const koboB = basketB.map(toKobo).reduce((a, b) => a + b, 0);

const naiveThirds = roundEach(10000, 3);              // ₦100.00 three ways
const thirds = allocate(10000, [1, 1, 1]);
const centres = allocate(999999, [3, 5, 7]);          // ₦9,999.99 as 3 : 5 : 7
const exactCentres = [3, 5, 7].map((w) => (999999 * w) / 15);
const drift = centres.map((share, i) => Math.abs(share - exactCentres[i]));

// 7.5% VAT taken back out of a VAT-inclusive price. Round the net, and let the
// VAT be whatever is left, so the two halves always reconstruct the price.
const RATE = 0.075;
const netOf = (gross) => Math.round(gross / (1 + RATE));
const vatOf = (gross) => gross - netOf(gross);

// What happens if you round both halves instead?
let bothRounded = 0;
let firstLoss = 0;
for (let gross = 1; gross <= 10000; gross++) {
  const net = netOf(gross);
  if (net + Math.round(net * RATE) !== gross) {
    bothRounded++;
    if (firstLoss === 0) firstLoss = gross;
  }
}

console.log('basket A     :', floatA, 'kobo total', koboA, 'agree:', floatA === koboA / 100);
console.log('basket B     :', floatB, 'kobo total', koboB, 'agree:', floatB === koboB / 100);
console.log('naive thirds :', naiveThirds, 'sum', naiveThirds.reduce((a, b) => a + b, 0));
console.log('allocated    :', thirds, 'sum', thirds.reduce((a, b) => a + b, 0));
console.log('3 : 5 : 7    :', centres, 'sum', centres.reduce((a, b) => a + b, 0));
console.log('exact shares :', exactCentres, 'drift', drift);
console.log('VAT out of   :', naira(5375), '-> net', naira(netOf(5375)), 'VAT', naira(vatOf(5375)));
console.log('both rounded :', bothRounded, 'of the first 10000 prices fail, from', firstLoss, 'kobo');

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('one basket of naira floats happens to add up exactly', [floatA === 14541.91, koboA], [true, 1454191]);
test('the next basket, priced the same way, does not', [floatB, floatB === 15540.1, koboB], [15540.099999999999, false, 1554010]);
test('the same intermittency in miniature: one sum misses, one hits', [0.1 + 0.2 === 0.3, 4500 + 0.1 + 0.2 === 4500.3], [false, true]);
test('rounding three equal shares of ₦100.00 loses a kobo', [naiveThirds, naiveThirds.reduce((a, b) => a + b, 0)], [[3333, 3333, 3333], 9999]);
test('largest remainder hands out all 10000, at the cost of a lopsided share', [thirds, thirds.reduce((a, b) => a + b, 0)], [[3334, 3333, 3333], 10000]);
test('a 3 : 5 : 7 split of ₦9,999.99 adds back to the invoice exactly', [centres, centres.reduce((a, b) => a + b, 0)], [[200000, 333333, 466666], 999999]);
test('and no cost centre is more than a kobo from its true proportion', drift.every((d) => d < 1), true);
test('VAT out of an inclusive ₦53.75 is 5000 net plus 375, which reconstructs it', [netOf(5375), vatOf(5375), netOf(5375) + vatOf(5375), naira(5375)], [5000, 375, 5375, '₦53.75']);
test('rounding both halves instead fails on 698 of the first 10000 prices, from 7 kobo up', [bothRounded, firstLoss], [698, 7]);

The headline is the second assertion sitting next to the first. Basket A adds up to 14541.91 in floats, exactly; basket B, three prices written the same way, comes out 15540.099999999999. Float error in money is intermittent, which is worse than being reliable: the bug passes your test suite on Monday's prices and drops a kobo on Tuesday's. 0.1 + 0.2 !== 0.3 is the famous case, but 4500 + 0.1 + 0.2 === 4500.3 is also true, so "floats are always wrong" is not a rule you can lean on either. Integer kobo, as exercise 15 set out, removes the question.

Integers do not remove the division problem, though, and that is what the rest of this is. ₦100.00 does not divide by three. Rounding each share gives three of 3333 and a kobo left in your hand; the largest-remainder rule floors every share, counts the shortfall, and hands those kobo to the shares with the biggest discarded fraction — so the parts always sum to the whole and no share is off by more than one kobo. The cost is that one person gets 3334, which is a policy you must be able to defend, not an accident.

The VAT split is the same rule in a smaller frame: round one part, derive the other by subtraction. Round both and 698 of the first 10000 prices no longer reconstruct — the first is 7 kobo, where a net of 7 and a VAT of 1 add to 8. That is a receipt whose lines do not add up to its total, and it is the single most common bug in billing code.

Common mistakes

  • Adding prices as decimals. It works for some baskets and not others. Convert to kobo first.
  • Rounding each share on its own. The shares no longer add up to the total.
  • Rounding both halves of a split. Round one part and get the other by subtraction.

Try it yourself

  1. Split ₦1.00 between seven people with allocate. How many get 15 kobo?
  2. Split ₦250.00 in the ratio 1 : 2 : 2 : 5 and check that the shares add up.
  3. Add up a basket of five prices of your own, once as floats and once in kobo, and see whether they agree.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.