Emmanuel Akinfulubi

JavaScriptBasic

Calculate a shopping cart total with tax in JavaScript

Beginner · 3 min read

Every online shop has a cart that adds up the items, works out the tax and shows a total. It sounds like the easiest code you will ever write. It is easy, but there is a trap in how computers store decimal numbers, and if you fall into it your totals can be off by a kobo or a cent with no obvious reason.

In this tutorial you will write a function called bill that takes a list of prices and returns the subtotal, the tax at 7.5% and the total. You need to know what a function, an array and an object are. The reduce method and the money trick are explained below.

The 0.1 + 0.2 problem

Try this:

JavaScript

console.log(0.1 + 0.2);         // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false

This is not a JavaScript bug. Computers store numbers in binary (base 2), and some decimals, like 0.1, can't be written exactly in binary, the same way 1/3 can't be written exactly in decimal (0.3333…). The stored value is very slightly off, and adding prices adds up the tiny errors.

The fix: count the smallest unit

Whole numbers don't have this problem. So instead of storing ₦850.50 as 850.5, store it as 85050 kobo (100 kobo make one naira). The same idea works for dollars and cents. Do all the adding in whole kobo, and divide by 100 only at the very end, when you show the total to a person.

Here is the exercise. Try it yourself first if you like, or build it with the steps below.

8 Add up a shopping list

easy

Given a list of item prices, produce the subtotal, a tax amount and the total. Keep the money arithmetic honest.

Stuck? Three hints, smallest first
  1. 1. Floating-point addition is not exact: 0.1 + 0.2 is not 0.3.
  2. 2. Work in the smallest unit — kobo, or cents — as whole numbers, and divide only for display.
  3. 3. reduce is the natural way to sum an array.

Step 1: add up the prices

reduce walks through an array and builds up one value. You give it a function and a starting value. The function gets the total so far and the next item, and returns the new total.

Step 1

const prices = [120000, 85050, 9999]; // ₦1200.00, ₦850.50 and ₦99.99, in kobo
const subtotal = prices.reduce((n, p) => n + p, 0);
console.log(subtotal); // 215049

The 0 is the starting value. It also means an empty cart adds up to 0 instead of causing an error.

Step 2: work out the tax

Tax at 7.5% is the subtotal times 0.075. That gives a fraction of a kobo, which nobody can pay, so round it to a whole kobo once.

Step 2

const subtotal = 215049;
console.log(subtotal * 0.075);             // 16128.675
console.log(Math.round(subtotal * 0.075)); // 16129

Round once, at this one point. Rounding the tax on each item and then adding can give a slightly different total.

Step 3: build the function

Return everything the cart page needs in one object. A default parameter, taxRate = 0.075, means callers can leave the rate out and get 7.5%.

Step 3

function bill(pricesInKobo, taxRate = 0.075) {
  const subtotal = pricesInKobo.reduce((n, p) => n + p, 0);
  const tax = Math.round(subtotal * taxRate);
  return {
    subtotal,
    tax,
    total: subtotal + tax,
  };
}

console.log(bill([120000, 85050, 9999]));
// { subtotal: 215049, tax: 16129, total: 231178 }

Writing subtotal, on its own inside the object is a shortcut for subtotal: subtotal.

Step 4: format for display

Only now do we divide by 100. toFixed(2) turns the number into text with exactly two decimal places.

Step 4

const total = 231178;
console.log(`₦${(total / 100).toFixed(2)}`); // ₦2311.78

The full answer adds this as a display field on the returned object. Keep it as the last step. If you divide earlier and keep calculating with the decimal, the rounding errors come back.

The full solution

The complete answer starts by showing the 0.1 + 0.2 problem, then builds the bill in kobo and prints each part. Press Run to see the output.

The answer

// The problem, first. This is real and it bites people constantly:
console.log('0.1 + 0.2 =', 0.1 + 0.2);
console.log('is that 0.3?', 0.1 + 0.2 === 0.3);

// So work in whole kobo and divide only at the very end.
function bill(pricesInKobo, taxRate = 0.075) {
  const subtotal = pricesInKobo.reduce((n, p) => n + p, 0);
  const tax = Math.round(subtotal * taxRate);      // round once, to a whole unit
  return {
    subtotal,
    tax,
    total: subtotal + tax,
    display: `₦${((subtotal + tax) / 100).toFixed(2)}`,
  };
}

// Three items at 1200.00, 850.50 and 99.99 naira, written in kobo.
const out = bill([120000, 85050, 9999]);

console.log('subtotal kobo:', out.subtotal);
console.log('tax kobo     :', out.tax);
console.log('total kobo   :', out.total);
console.log('for the eye  :', out.display);

Output


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

6 checks

test('floating point really is inexact', 0.1 + 0.2 === 0.3, false);
test('subtotal is exact in kobo', out.subtotal, 215049);
test('tax rounded to a whole kobo', out.tax, 16129);
test('total', out.total, 231178);
test('displayed once, at the end', out.display, '₦2311.78');
test('an empty list totals zero', bill([]).total, 0);

The first two lines are not a digression. 0.1 + 0.2 === 0.3 is false in every language that uses binary floating point, which is nearly all of them. Adding prices as decimals accumulates that error until a total is a kobo out and nobody can explain why. Store money as whole minor units, do all arithmetic on integers, and divide once for display.

Common mistakes

  • Adding prices as decimals. 850.5 + 99.99 may be a tiny bit off. Store money as whole kobo or cents.
  • Comparing money with === after decimal maths. 0.1 + 0.2 === 0.3 is false. With whole numbers the comparison is exact.
  • Rounding too late or too often. Round the tax once to a whole kobo, and divide by 100 only for display.

Try it yourself

  1. Add a discount: a discountRate parameter that takes a percentage off the subtotal before tax. Round it to a whole kobo too.
  2. Accept items as { name, priceKobo, quantity } objects and multiply price by quantity in the reduce.
  3. Change display to use thousands separators, so the total shows as ₦2,311.78. Look up toLocaleString.

Keep practising

Newsletter

New writing, when it lands.

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