Split a bill into equal shares in JavaScript
Intermediate · 4 min read
Three friends share a ₦12,500 bill. Each owes a third, which is ₦4,166.666..., a number that never ends. You can't charge anyone a fraction of a kobo, so the shares have to be rounded somehow, and they still have to add up to exactly the bill. Split-payment apps, group bookings and rent calculators all face this.
In this tutorial you will write splitBill(totalKobo, people), which returns one whole-kobo share per person, and then prove that the shares add back up to the bill. Money is in kobo (100 kobo make one naira). You need to know what an array is, what Math.floor and % do (rounding down, and the remainder after dividing), and how reduce adds up an array.
Why simple rounding doesn't work
₦12,500 is 1,250,000 kobo. Divide by 3 and you get 416,666.666... kobo each.
- Round every share up to 416,667 and the three shares add up to 1,250,001. You collected one kobo too many.
- Round every share down to 416,666 and they add up to 1,249,998. You are two kobo short.
Whichever way you round, if everyone pays the same, the total is wrong. So not everyone can pay the same.
The idea: share out the leftover kobo
Divide and round down to get a base share. The remainder tells you how many kobo are left over after everyone pays the base. Give those leftover kobo out one at a time: the first person pays one extra kobo, the second person pays one extra, until they run out.
For 1,250,000 kobo and 3 people: the base is 416,666 and the remainder is 2. So two people pay 416,667 and one pays 416,666.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
81 Split a bill so the kobo add back up
fairSplit a bill of ₦12,500 three ways. Every share must be a whole number of kobo, and the shares must add back to exactly the bill. Also exercise 63, which argues for holding money in kobo; here the angle is division, where the argument is unanswerable.
Stuck? Three hints, smallest first
- 1. Divide into a base share with
Math.floor, then look at the remainder. - 2. The remainder is how many people pay one kobo more than the rest.
- 3. Add the shares back up and compare with the total. That check is the whole exercise.
Step 1: base share and remainder
const BILL = 12_500_00;
const base = Math.floor(BILL / 3);
const extra = BILL % 3;
console.log(base, extra); // 416666 2
The underscores in 12_500_00 only make it easy to read: naira, then kobo. extra is the number of people who pay one kobo more.
Step 2: build the shares
Array.from({ length: people }, fn) makes an array of that length, calling fn for each position to fill it in:
function splitBill(totalKobo, people) {
const base = Math.floor(totalKobo / people);
const extra = totalKobo % people;
return Array.from({ length: people }, (_, i) => base + (i < extra ? 1 : 0));
}
console.log(splitBill(12_500_00, 3)); // [ 416667, 416667, 416666 ]
console.log(splitBill(900_00, 3)); // [ 30000, 30000, 30000 ]
console.log(splitBill(12_500_00, 1)); // [ 1250000 ]
The function gets two arguments: the current item (unused, so it is named _) and the position i. People at positions below extra get one more kobo. When the bill divides evenly, extra is 0 and everyone pays the same.
Step 3: prove it adds up
The whole point is that the parts add back to the bill. Check it:
function splitBill(totalKobo, people) {
const base = Math.floor(totalKobo / people);
const extra = totalKobo % people;
return Array.from({ length: people }, (_, i) => base + (i < extra ? 1 : 0));
}
const shares = splitBill(12_500_00, 3);
console.log(shares.reduce((a, b) => a + b, 0)); // 1250000
console.log(416667 * 3); // 1250001
The shares add to exactly 1,250,000. The second line is what you get by rounding every share the same way: one kobo too many.
Step 4: the naira trap
Try the same split in naira with decimals, and round with toFixed(2):
console.log((12500 / 3).toFixed(2)); // 4166.67
console.log(typeof (12500 / 3).toFixed(2)); // string
console.log(Number((12500 / 3).toFixed(2)) * 3); // 12500.01
Two problems hide here. toFixed gives text, not a number, so '4166.67' looks right but can't be used in math until you turn it back. And once you do, three of them make ₦12,500.01. The extra kobo is back, and it is easy to miss because each share looks fine on its own.
Step 5: refuse bad input
A total that isn't a whole number of kobo means some earlier code did math in naira. A count of people below 1 makes no sense. Check both before dividing:
function checkInput(totalKobo, people) {
if (!Number.isInteger(totalKobo) || totalKobo < 0) {
throw new TypeError('the total must be a whole number of kobo');
}
if (!Number.isInteger(people) || people < 1) {
throw new RangeError('need at least one person');
}
}
try {
checkInput(4166.67, 3);
} catch (err) {
console.log(err.message); // the total must be a whole number of kobo
}
In the full answer, these checks sit at the top of splitBill.
The full solution
The answer panel has splitBill with both checks, prints the shares and their sum, and shows the naira version going wrong. Its checks cover the odd kobo going to the first people, an even split, one person, the toFixed string, and a fractional total. Press Run to see the output.
function splitBill(totalKobo, people) {
if (!Number.isInteger(totalKobo) || totalKobo < 0) {
throw new TypeError('the total must be a whole number of kobo');
}
if (!Number.isInteger(people) || people < 1) {
throw new RangeError('need at least one person');
}
const base = Math.floor(totalKobo / people);
const extra = totalKobo % people; // this many pay one kobo more
return Array.from({ length: people }, (_, i) => base + (i < extra ? 1 : 0));
}
const BILL = 12_500_00; // twelve and a half thousand naira, in kobo
const shares = splitBill(BILL, 3);
let refused = '';
try {
splitBill(4166.67, 3);
} catch (err) {
refused = err.message;
}
console.log('shares:', shares, 'sum:', shares.reduce((a, b) => a + b, 0));
console.log('the naira route:', (12500 / 3).toFixed(2), 'x 3 =', Number((12500 / 3).toFixed(2)) * 3);
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('the odd kobo go to the front of the queue', shares, [416667, 416667, 416666]);
test('and the shares add back to the bill exactly', shares.reduce((a, b) => a + b, 0), BILL);
test('an exact split gives everyone the same', splitBill(900_00, 3), [30000, 30000, 30000]);
test('one person pays the lot', splitBill(BILL, 1), [1250000]);
test('rounding each share instead overcharges by a kobo', 416667 * 3, 1250001);
test('toFixed hands back a string, not a number', typeof (12500 / 3).toFixed(2), 'string');
test('and three of those do not add up to the bill', Number((12500 / 3).toFixed(2)) * 3, 12500.01);
test('a fractional total is refused rather than rounded away', refused.includes('whole number'), true);
Division is where naira-with-decimals finally breaks. ₦12,500 over three people is ₦4,166.666…, and every way of rounding that to a printable amount is wrong: round each share up and you collect ₦12,500.01, round down and you are a kobo short. The money has to go somewhere, so decide where — here the first extra people pay one kobo more, which is what a POS receipt does.
toFixed being a string is the second trap, and it hides the first: '4166.67' looks like a number, so it gets multiplied back later and the penny reappears as 12500.01. Keep integers in kobo all the way through, divide with Math.floor and a remainder, and make "the parts sum to the whole" an assertion rather than a hope.
Common mistakes
- Rounding every share the same way. The shares then add up to more or less than the bill.
- Doing the split in naira with
toFixed. It gives text, and adding the rounded shares back gives the wrong total. - Never checking the sum. "The shares add up to the bill" should be a test, not a hope.
Try it yourself
- Split ₦10,000 four ways and ₦10,000.01 three ways, and check each sum.
- Change
splitBillso the extra kobo go to the last people instead of the first. - Write
splitWithTip(totalKobo, people, tipPercent)that adds a tip (rounded to a whole kobo) before splitting.