Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Immutable Money class in kobo in JavaScript

117 Money in kobo, and a split that loses nothing

hard

Never store money in a float. Build an immutable Money type holding whole kobo, with plus, minus, times, a splitInto(n) that hands the remainder out rather than dropping it, an allocate for uneven shares, and a format that groups thousands. Prove the arithmetic is exact where floats are not, and prove the property that matters most: the parts of a split always add back up to the whole, for any amount and any number of parts, positive or negative. Then look closely at how you round, because Math.round is not symmetric about zero.

Stuck? Three hints, smallest first
  1. 1. One integer field. Every operation returns a new Money and the constructor refuses anything that is not a whole number, so a fraction of a kobo can never get in.
  2. 2. To split, take the floor share for everybody and then hand out the leftover kobo one at a time. The remainder is always smaller than the number of parts, so somebody gets at most one extra.
  3. 3. Math.round(-2.5) is -2, not -3: it rounds towards positive infinity on a tie. For money you want ties to go away from zero, so a refund rounds like a charge.

The answer

const SYMBOLS = { NGN: '\u20a6', USD: '$' };
const roundHalfAway = (n) => (n < 0 ? -Math.round(-n) : Math.round(n));

class Money {
  constructor(kobo, currency = 'NGN') {
    if (!Number.isInteger(kobo)) {
      throw new TypeError('kobo must be a whole number, got ' + kobo);
    }
    if (!SYMBOLS[currency]) throw new RangeError('unknown currency ' + currency);
    this.kobo = kobo;
    this.currency = currency;
    Object.freeze(this);
  }

  static fromNaira(naira, currency = 'NGN') {
    return new Money(roundHalfAway(naira * 100), currency);
  }

  sameCurrency(other) {
    if (other.currency !== this.currency) {
      throw new TypeError('cannot mix ' + this.currency + ' and ' + other.currency);
    }
  }

  plus(other) { this.sameCurrency(other); return new Money(this.kobo + other.kobo, this.currency); }
  minus(other) { this.sameCurrency(other); return new Money(this.kobo - other.kobo, this.currency); }
  times(factor) { return new Money(roundHalfAway(this.kobo * factor), this.currency); }

  splitInto(parts) {
    if (!Number.isInteger(parts) || parts < 1) throw new RangeError('parts must be a positive whole number');
    const base = Math.trunc(this.kobo / parts);
    let left = this.kobo - base * parts;              // same sign as the amount
    const step = left < 0 ? -1 : 1;
    const out = [];
    for (let i = 0; i < parts; i++) {
      const extra = left === 0 ? 0 : step;
      left -= extra;
      out.push(new Money(base + extra, this.currency));
    }
    return out;
  }

  allocate(ratios) {
    if (!ratios.length) throw new RangeError('need at least one ratio');
    const whole = ratios.reduce((a, b) => a + b, 0);
    let left = this.kobo;
    const shares = ratios.map((r) => {
      const share = Math.trunc((this.kobo * r) / whole);
      left -= share;
      return share;
    });
    for (let i = 0; left !== 0; i = (i + 1) % shares.length) {
      const step = left < 0 ? -1 : 1;
      shares[i] += step;
      left -= step;
    }
    return shares.map((k) => new Money(k, this.currency));
  }

  format() {
    const sign = this.kobo < 0 ? '-' : '';
    const size = Math.abs(this.kobo);
    const naira = String(Math.trunc(size / 100)).replace(/\B(?=([0-9]{3})+(?![0-9]))/g, ',');
    const kobo = String(size % 100).padStart(2, '0');
    return sign + SYMBOLS[this.currency] + naira + '.' + kobo;
  }

  toJSON() { return { kobo: this.kobo, currency: this.currency }; }
}

const errorOf = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name + ': ' + err.message; } };
const kobos = (list) => list.map((m) => m.kobo);
const sumOf = (list) => list.reduce((a, m) => a + m.kobo, 0);

const tenKobo = new Money(10);
const twentyKobo = new Money(20);
const floatVersus = [0.1 + 0.2 === 0.3, tenKobo.plus(twentyKobo).kobo];

let floatTotal = 0;
let koboTotal = new Money(0);
for (let i = 0; i < 10; i++) { floatTotal += 0.1; koboTotal = koboTotal.plus(tenKobo); }
const tenAdditions = [floatTotal === 1, koboTotal.kobo, koboTotal.format()];

const tenNaira = Money.fromNaira(10);
const threeWays = tenNaira.splitInto(3);
const splitStory = [kobos(threeWays), sumOf(threeWays), sumOf(threeWays) === tenNaira.kobo];

const refund = new Money(-1000);
const refundSplit = refund.splitInto(3);
const refundStory = [kobos(refundSplit), sumOf(refundSplit)];

// The property, over every amount and every number of parts in a range.
let nothingEverLost = true;
for (let amount = -37; amount <= 37; amount++) {
  for (let parts = 1; parts <= 7; parts++) {
    const pieces = new Money(amount).splitInto(parts);
    if (sumOf(pieces) !== amount) nothingEverLost = false;
    if (pieces.length !== parts) nothingEverLost = false;
  }
}

const rent = Money.fromNaira(1000);
const uneven = rent.allocate([3, 2, 1]);
const allocateStory = [kobos(uneven), sumOf(uneven) === rent.kobo];

const formatting = [
  Money.fromNaira(1234567.05).format(),
  new Money(-4550).format(),
  new Money(7).format(),
  new Money(0).format(),
  new Money(199, 'USD').format(),
];

const roundingTrap = [Math.round(-2.5), Math.round(2.5), roundHalfAway(-2.5), roundHalfAway(2.5)];
const vat = [new Money(45000).times(0.075).kobo, new Money(1).times(0.075).kobo, new Money(-45000).times(0.075).kobo];

const refusals = [
  errorOf(() => new Money(10.5)),
  errorOf(() => new Money(100).plus(new Money(100, 'USD'))),
  errorOf(() => new Money(100).splitInto(0)),
];
const frozen = errorOf(() => { tenKobo.kobo = 9999; });
const projected = [JSON.parse(JSON.stringify(new Money(45000))), Object.isFrozen(tenKobo)];

console.log('floats vs kobo :', floatVersus, tenAdditions);
console.log('split of 1000  :', splitStory);
console.log('allocate 3:2:1 :', allocateStory);
console.log('formatted      :', formatting.join('  '));

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('0.1 + 0.2 is not 0.3, while 10 kobo plus 20 kobo is exactly 30', floatVersus, [false, 30]);
test('and ten additions land on a whole naira in kobo but not in floats', tenAdditions, [false, 100, '\u20a61.00']);
test('splitting 1000 kobo three ways gives the leftover kobo away, not up', splitStory, [[334, 333, 333], 1000, true]);
test('a refund splits the same way, with the extra kobo on the same side of zero', refundStory, [[-334, -333, -333], -1000]);
test('for every amount from -37 to 37 and every part count to 7, the pieces add back to the whole', nothingEverLost, true);
test('an uneven 3:2:1 allocation of 100000 kobo also loses nothing', allocateStory, [[50001, 33333, 16666], true]);
test('formatting groups thousands, pads kobo, and puts the sign before the symbol', formatting, ['\u20a61,234,567.05', '-\u20a645.50', '\u20a60.07', '\u20a60.00', '$1.99']);
test('Math.round is not symmetric about zero, so ties are rounded away from it instead', [roundingTrap, vat], [[-2, 3, -3, 3], [3375, 0, -3375]]);
test('a fraction of a kobo, a mixed currency and a zero split are all refused, and the value is frozen', [refusals, frozen, projected], [['TypeError: kobo must be a whole number, got 10.5', 'TypeError: cannot mix NGN and USD', 'RangeError: parts must be a positive whole number'], 'TypeError: Cannot assign to read only property \'kobo\' of object \'#<Money>\'', [{ kobo: 45000, currency: 'NGN' }, true]]);

Money in a float is wrong before you do anything with it, because 0.1 has no exact binary representation. The first two assertions are that in two forms: 0.1 + 0.2 !== 0.3, and ten additions of ten kobo land on exactly ₦1.00 while ten additions of 0.1 do not land on 1. Storing the smallest unit as an integer removes the whole class of problem — every amount is exact, every comparison is exact, and the error can only enter at the two places you choose to round.

The fifth assertion is the one worth writing for real code. Rather than checking a handful of splits, it checks the property — the pieces add back up to the whole, and there are as many pieces as asked for — over 75 amounts and 7 part counts, negatives included. That is what catches the two classic bugs at once: dividing and rounding each share, which loses kobo, and giving the remainder to one person as a lump, which is right in total and wrong per person. Handing the leftover out one kobo at a time is the only version that is both exact and fair, and for a payments system the exactness is auditable: somebody will reconcile it.

Math.round is the sharp edge nobody expects. It rounds a tie towards positive infinity, so Math.round(2.5) is 3 and Math.round(-2.5) is -2 — the two are not mirror images. Applied to money that means a charge of ₦0.025 rounds up and a refund of the same amount rounds down, so charging and refunding the same thing does not return you to zero. roundHalfAway makes the operation symmetric, and the eighth assertion holds it to that. Note too that VAT on a single kobo rounds to zero: rounding to the smallest unit always loses something, so the honest design is to choose where that happens rather than let it happen everywhere.

Two smaller points. Object.freeze in the constructor plus operations that return new instances makes the value type behave like a number, and under the strict mode these panels run in an accidental write throws instead of silently corrupting a balance. And toJSON is what lets the amount cross a wire without a currency going missing — a bare number in an API response is an amount whose unit you have to guess.

Newsletter

New writing, when it lands.

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