Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Cart total with discount and VAT in kobo in JavaScript

94 A basket total in kobo, with a discount and 7.5% VAT

fair

Total a basket entirely in integer kobo: line totals, a percentage discount off the subtotal, then VAT at 7.5% on what is left. Express the rates in basis points so nothing needs a fractional multiplier, round exactly once where a half-kobo appears, and format the result as naira with thousand separators. Then say why none of this is done in naira with a decimal point.

Stuck? Three hints, smallest first
  1. 1. Keep every amount an integer number of kobo. Convert to naira only when printing.
  2. 2. A percentage as basis points — 750 for 7.5% — turns × 0.075 into × 750 / 10000.
  3. 3. replace(/\B(?=(\d{3})+(?!\d))/g, ',') inserts the separators from the right.

The answer

const naira = (kobo) =>
  '\u20a6' + (kobo / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');

const VAT_BPS = 750;   // 7.5%, in basis points

function totalBasket(lines, { discountBps = 0, vatBps = VAT_BPS } = {}) {
  const subtotalKobo = lines.reduce((sum, line) => sum + line.unitKobo * line.qty, 0);
  const discountKobo = Math.round((subtotalKobo * discountBps) / 10000);
  const taxableKobo = subtotalKobo - discountKobo;
  const vatKobo = Math.round((taxableKobo * vatBps) / 10000);
  return {
    subtotalKobo,
    discountKobo,
    taxableKobo,
    vatKobo,
    totalKobo: taxableKobo + vatKobo,
  };
}

const basket = [
  { name: 'Gari, 5kg', unitKobo: 450000, qty: 2 },
  { name: 'Palm oil, 1L', unitKobo: 285000, qty: 1 },
  { name: 'Sachet water, bag', unitKobo: 35000, qty: 3 },
];

const plain = totalBasket(basket, { discountBps: 0 });
const discounted = totalBasket(basket, { discountBps: 1000 });     // 10% off
const everyFieldIsAnInteger = Object.values(discounted).every(Number.isInteger);

const freeOfCharge = totalBasket(basket, { discountBps: 10000 });  // 100% off
const emptyBasket = totalBasket([], { discountBps: 1000 });

// A half-kobo really does turn up: 7.5% of 1999 kobo is 149.925.
const oneOddItem = totalBasket([{ name: 'Sachet, single', unitKobo: 1999, qty: 1 }]);
const unrounded = (1999 * VAT_BPS) / 10000;

console.log('subtotal :', naira(plain.subtotalKobo));
console.log('10% off  :', naira(discounted.discountKobo), '| VAT', naira(discounted.vatKobo));
console.log('to pay   :', naira(discounted.totalKobo));
console.log('one item :', oneOddItem.vatKobo, 'kobo of VAT on', unrounded, 'exactly');

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('the subtotal is a whole number of kobo', [plain.subtotalKobo, naira(plain.subtotalKobo)], [1290000, '\u20a612,900.00']);
test('VAT on the undiscounted basket', [plain.vatKobo, plain.totalKobo], [96750, 1386750]);
test('10% off comes before VAT, so the tax base shrinks too', [discounted.discountKobo, discounted.taxableKobo, discounted.vatKobo], [129000, 1161000, 87075]);
test('and the total prints with separators and exactly two decimals', naira(discounted.totalKobo), '\u20a612,480.75');
test('every field stayed an integer, which is the whole point of working in kobo', everyFieldIsAnInteger, true);
test('a half-kobo is rounded once, at the end, rather than carried', [unrounded, oneOddItem.vatKobo, oneOddItem.totalKobo], [149.925, 150, 2149]);
test('100% off leaves nothing to tax and nothing to pay', [freeOfCharge.taxableKobo, freeOfCharge.vatKobo, freeOfCharge.totalKobo], [0, 0, 0]);
test('an empty basket totals to zero rather than NaN', [emptyBasket.subtotalKobo, naira(emptyBasket.totalKobo)], [0, '\u20a60.00']);
test('and the reason for all of it: naira as a float cannot even add up', 0.1 + 0.2 === 0.3, false);

Money in floats is not a style preference. 0.1 + 0.2 is not 0.3, and the error compounds across a basket, so a subtotal computed in naira and a total computed from the same lines can disagree by a kobo — which is a reconciliation failure, not a rounding nicety. Integers in the smallest unit remove the entire class of bug: every amount here is exact, and the fifth assertion is the proof.

Basis points do the same job for rates. × 750 / 10000 keeps the multiplication in integers until the single division, where × 0.075 is already inexact before the multiplication starts. Storing the rate as an integer also makes it safe to put in a database column and compare for equality.

Rounding once, at the end, and in a defined direction, is the third rule. The sixth assertion is the case: 7.5% of 1999 kobo is 149.925, and something has to decide. Rounding each line and then summing gives a different answer from summing and then rounding, and tax authorities care which you did. Discount before VAT is likewise a rule, not a choice — tax is charged on what the customer actually pays. Printing is the last step and belongs nowhere near the arithmetic. toFixed(2) for the decimals, one regex for the grouping. Intl.NumberFormat with currency: 'NGN' is the fuller answer for a real UI, and it is deliberately avoided here because its exact output — symbol, spacing, minus sign placement — depends on the platform's locale data, which is not something a test should assert.

Newsletter

New writing, when it lands.

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