How to Calculate Tax With JavaScript

The best way to calculate tax with JavaScript (and the pitfalls to watch out for as you do).

Published Categorized as JavaScript, Web & Code

Let’s be honest here: Taxes are everyone’s favorite topic. It’s no different in the world of development. If you have been wondering how to calculate taxes with JavaScript, this tutorial shows you how to do it—with code samples and the keys to getting it right.

Understanding Tax Logic

Sales tax, Value-Added Tax (VAT), Goods and Services Tax (GST)…

If you’re working on an application where these taxes need to be considered, the names alone can be daunting. But the good news is that they don’t have to be. The logic behind taxes is actually pretty simple and sound.

Suppose you sell $100.00 worth of goods to a consumer. Someone in the government has decided to tax all sales to consumers at a rate of 20%. So the shortest path to the final price you must charge is to multiply the cart value by 1.2, which equals 120% of the pre-tax sales price.

Nine times out of ten, you will have to apply a flat tax rate to the total value of the shopping cart. However—and this is where your business stakeholders need to be extremely clear about what they need—some governments tax different product categories at a different rate.

If bread is taxed at 0% and cheese at 20%, your JavaScript application’s logic will need to take this into account when calculating the final price.

Apply Tax on Total Cart Value

Assuming you know the total value of the cart and there’s a flat tax rate, what you need to do is take the value of the cart, calculate the tax due based on the tax rate, and add it to the value of the cart to get the final price.

// Set cart value (in our case, $49.99)
let cartValue = 49.99;
// Set tax rate (in our case, 7%)
let taxRate = 7;

// Calculate tax due
taxDue = cartValue * (taxRate / 100);
// Calculate final price
finalPrice = cartValue * (1 + (taxRate / 100));

// Output result to browser console
console.log("Cart value: $" + cartValue + "\nTax rate: " + taxRate + "%\nTax due: $" + taxDue + "\n\nFinal price: $" + finalPrice);

Note that you get a non-rounded number when using this method.

So this method will work fine if your application has to deal with whole numbers (for example, if the price is $100 and the tax rate is 20%), but less so with decimal numbers (like our example, with the price at $49.99 and the tax rate 7%).

It’s best that you see it for yourself. Here’s a screenshot from the example code snippet above that illustrates what I mean:

However you look at it, this isn’t the most user-friendly way to display the tax due and the final price.

In a real-world implementation scenario, your application will probably have to deal with decimal prices and all kinds of weird tax rates. So you should consider rounding up these numbers before they’re stored in a database and/or shown to the user.

To round the tax due and final price down to two decimals, you can use the toFixed() method, applying the following hack to keep it from converting the values into strings.

Here’s how this works:

// Set cart value (in our case, $49.99)
let cartValue = 49.99;
// Set tax rate (in our case, 7%)
let taxRate = 7;

// Calculate tax due
taxDue = cartValue * (taxRate / 100);
roundedTaxDue = +(taxDue.toFixed(2));
// Calculate final price
finalPrice = cartValue * (1 + (taxRate / 100));
roundedFinalPrice = +(finalPrice.toFixed(2));

// Output result to browser console
console.log("Cart value: $" + cartValue + "\nTax rate: " + taxRate + "%\nTax due: $" + roundedTaxDue + "\n\nFinal price: $" + roundedFinalPrice);

As expected, the result is user-friendly numbers:

Calculate Cart Value and Apply Variable Tax

Below is a more elaborate code sample for when you need to calculate tax for three categories of products: one taxed at a rate of 18% (cat1), the other at 12% (cat2), and still the other at 0% (cat3).

// Category 1 value (taxed at 18%)
let cat1 = 52.3;
let taxRate1 = 18;
// Category 2 value (taxed at 12%)
let cat2 = 17.21;
let taxRate2 = 12;
// Category 3 value (taxed at 0%)
let cat3 = 5;
// NOTE THAT A 0% TAX RATE TRANSLATES TO A VALUE OF 1 HERE!
let taxRate3 = 1;

// Calculate cart
let cartValue = cat1 + cat2 + cat3;
let roundedCartValue = +(cartValue.toFixed(2));
// Calculate tax due
let taxDue = cat1 * (taxRate1 / 100) + cat2 * (taxRate2 / 100) + cat3 * (taxRate3 / 100);
let roundedTaxDue = +(cat1.toFixed(2));
// Calculate final price
let finalPrice = cartValue + taxDue;
let roundedFinalPrice = +(finalPrice.toFixed(2));

// Output result to browser console
console.log("Cart value: $" + roundedCartValue + "\nTax Due: $" + roundedTaxDue + "\n\nFinal price: $" + roundedFinalPrice);

You probably saw that in the figures above, a tax rate of 0% corresponds to a multiplication factor of 1. This is because of the way we calculate the tax due. If you multiply a number by 0, the result is 0. If you multiply a number by 1, the result is the original number (effectively, that’s a tax rate of 0%).

By Dim Nikov

Content creator with marketing and web development skills to pay the bills.

Leave a comment

Your email address will not be published. Required fields are marked *