Emmanuel Akinfulubi

JavaScriptMath

Store prices as integers (kobo) in JavaScript

Intermediate · 4 min read

Money is the one place where a floating-point error turns into a complaint. Add ₦19.99, ₦5.75 and ₦3.40 with ordinary JavaScript numbers and the total is not quite ₦29.14. Every payment system, from small shops to banks, avoids this the same way: it stores amounts in the smallest unit, as whole numbers.

For naira, the smallest unit is the kobo, and one naira is 100 kobo. In this tutorial you will hold three prices as whole numbers of kobo, add them, apply 7.5% VAT, and format the total for a receipt. Then you will show that the same sum in naira goes wrong. You need to know map, reduce and toFixed.

Why whole numbers are safe

JavaScript stores numbers in binary, and most decimals, like 19.99, can't be stored exactly. Whole numbers can, all the way up to about nine thousand trillion. So if every amount is a whole number of kobo, adding, subtracting and multiplying by whole numbers are all exact.

The plan has three parts:

  1. Convert once at the edge. When a price comes in, turn naira into kobo.
  2. Do all the math in kobo.
  3. Convert back only for display.

Here is the exercise. Try it yourself first if you like, then read on and we will build it step by step.

15 Money belongs in integer kobo

fair

Hold three prices as integer kobo, add them, apply 7.5% VAT and format the total as naira. Then show a set of naira prices whose float total is wrong.

Stuck? Three hints, smallest first
  1. 1. One naira is 100 kobo. Convert once at the boundary with Math.round(naira * 100).
  2. 2. Every sum, discount and split happens on the integers; divide by 100 only for display.
  3. 3. 19.99 + 5.75 + 3.4 is the kind of total that does not come out exact.

Step 1: the total that goes wrong

First, see the problem:

Step 1

const prices = [19.99, 5.75, 3.4];
const floatTotal = prices.reduce((a, b) => a + b, 0);
console.log(floatTotal);          // 29.139999999999997
console.log(floatTotal === 29.14); // false

reduce adds the items one by one, starting from 0. The total is a hair short of 29.14, so an equality check against the expected total fails.

Step 2: convert naira to kobo

The obvious way is to multiply by 100. That is almost right:

Step 2

console.log(19.99 * 100);             // 1998.9999999999998
console.log(Math.round(19.99 * 100)); // 1999

19.99 is stored slightly low, so times 100 is slightly under 1999. If you chopped off the fraction you would lose a kobo. Math.round goes to the nearest whole number, which is always the one you meant. So the converter is:

JavaScript

const toKobo = (naira) => Math.round(naira * 100);
console.log([19.99, 5.75, 3.4].map(toKobo)); // [ 1999, 575, 340 ]

map runs toKobo on each price and gives back a new array.

Step 3: add in kobo

Step 3

const toKobo = (naira) => Math.round(naira * 100);
const inKobo = [19.99, 5.75, 3.4].map(toKobo);
const subtotal = inKobo.reduce((a, b) => a + b, 0);
console.log(subtotal); // 2914

Whole numbers added together give an exact whole number: 2914 kobo, which is ₦29.14 exactly.

Step 4: apply 7.5% VAT

7.5% of the subtotal is subtotal * 0.075. That is usually not a whole number of kobo, so you have to decide how to round it. Here we round to the nearest kobo:

Step 4

const subtotal = 2914;
console.log(subtotal * 0.075);             // 218.54999999999998
const vat = Math.round(subtotal * 0.075);
const total = subtotal + vat;
console.log(vat, total);                   // 219 3133

Rounding is the only moment a decimal appears, and it is rounded straight back to a whole number. Every value you keep, subtotal, vat and total, is a whole number of kobo.

Step 5: format for the receipt

Only now, when the total leaves your code, do you turn it back into naira:

Step 5

const naira = (kobo) => (kobo / 100).toFixed(2);
console.log(naira(3133)); // 31.33
console.log(naira(2914)); // 29.14

Dividing a whole number by 100 lands on the closest stored value to the right answer, and toFixed(2) turns it into a string with exactly two decimal places. That string is for display only. Don't add it to anything.

Step 6: check every value stayed whole

Number.isSafeInteger checks that a value is a whole number small enough to be stored exactly:

JavaScript

console.log([2914, 219, 3133].every(Number.isSafeInteger)); // true

The safe limit is 9,007,199,254,740,991 kobo, about ₦90 trillion, so running out of room is not a real worry.

The full solution

The answer panel converts the three prices to kobo, adds them, applies VAT, formats the total, and prints the naira total next to it so you can see the difference. The checks underneath confirm every value is exact, including that the float total fails an equality check. Press Run to see the output.

The answer

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

const prices = [19.99, 5.75, 3.4];
const inKobo = prices.map(toKobo);                 // [1999, 575, 340]
const subtotal = inKobo.reduce((a, b) => a + b, 0);
const vat = Math.round(subtotal * 0.075);          // 7.5%, to the nearest kobo
const total = subtotal + vat;

const floatTotal = prices.reduce((a, b) => a + b, 0);

console.log('prices     :', prices);
console.log('as kobo    :', inKobo);
console.log('subtotal   :', subtotal, 'kobo =', naira(subtotal));
console.log('VAT        :', vat, 'kobo');
console.log('total      :', total, 'kobo =', naira(total));
console.log('float total:', floatTotal, '<- and it should be 29.14');
console.log('a price times 100 direct:', 19.99 * 100);

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('each price becomes an exact integer of kobo', inKobo, [1999, 575, 340]);
test('the naive multiply would not have', 19.99 * 100, 1998.9999999999998);
test('adding integers is exact', subtotal, 2914);
test('where adding the floats is not', floatTotal, 29.139999999999997);
test('so the float total fails an equality check against 29.14', floatTotal === 29.14, false);
test('VAT at 7.5% of 2914 kobo, to the nearest kobo', vat, 219);
test('and the total stays an integer', total, 3133);
test('formatted for a receipt', naira(total), '31.33');
test('every intermediate value is a safe integer', [subtotal, vat, total].every(Number.isSafeInteger), true);

The rule is: convert to minor units at the edge of the system, do all arithmetic in integers, and format only when the value leaves. Integers below 253 are exact, so no sum, discount or split can drift — and 253 kobo is about ₦90 trillion, so the headroom is not the problem.

Math.round(naira * 100) is doing real work in the first assertion: 19.99 * 100 is 1998.9999999999998, and truncating that would lose a kobo on every conversion. Round, never truncate, when crossing from decimal to minor units.

Percentages are the remaining decision. Math.round(subtotal * 0.075) rounds VAT to the nearest kobo, which is a policy choice — exercise 106 shows the version where the rounded parts must add back to a fixed total.

Common mistakes

  • Converting with Math.floor or Math.trunc. Math.floor(19.99 * 100) is 1998, one kobo short. Always use Math.round.
  • Formatting too early. toFixed returns a string. Do all the math in kobo, then format once.
  • Forgetting to round a percentage. 2914 * 0.075 is not a whole number. Round VAT, discounts and shares to the kobo as soon as you work them out.

Try it yourself

  1. Add a 10% discount to the subtotal before VAT, in kobo, and print the new total.
  2. Split ₦100 between three people in kobo so the three shares add back to exactly 10000.
  3. Write parseNaira('1,250.50') that turns a string like that into 125050 kobo.

Keep practising

Newsletter

New writing, when it lands.

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