Calculate Percentage between Two Numbers in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20212 min read

banner

Photo by Raychan

Calculate Percentage between Two Numbers #

To calculate the percentage between two numbers, divide one number from the other and multiply the result by 100, e.g. (30 / 75) * 100. This shows what percent the first number is of the second, in the example - 30 is 40% of 75.

index.js
function isWhatPercentOf(numA, numB) { return (numA / numB) * 100; } // ๐Ÿ‘‡๏ธ `30` is 40% of `75` console.log(isWhatPercentOf(30, 75)); // ๐Ÿ‘‰๏ธ 40 // ๐Ÿ‘‡๏ธ `20` is 26.666% of `75` console.log(isWhatPercentOf(20, 75)); // ๐Ÿ‘‰๏ธ 26.666666... // โœ… Round to 2 decimals console.log(isWhatPercentOf(20, 75).toFixed(2)); // ๐Ÿ‘‰๏ธ "26.67" // โœ… Get percentage Increase / Decrease function getPercentageIncrease(numA, numB) { return ((numA - numB) / numB) * 100; } // ๐Ÿ‘‡๏ธ `50` is 66.66% increase from `30` console.log(getPercentageIncrease(50, 30)); // ๐Ÿ‘‰๏ธ 66.666 // ๐Ÿ‘‡๏ธ `50` is 50% decrease from `100` console.log(getPercentageIncrease(50, 100)); // ๐Ÿ‘‰๏ธ 66.666

The first function we created takes 2 numbers are returns what percent numberA is of numberB.

For example, 25 / 50 * 100 shows that 25 is 50% of 50.

index.js
// ๐Ÿ‘‡๏ธ `25` is 50% of `50` console.log((25 / 50) * 100);

When calculating percentages between two numbers, you might need to round to a specific number of digits after the decimal.

You can use the Number.toFixed method to achieve this.

index.js
const percentage = (20 / 75) * 100; console.log(percentage); // ๐Ÿ‘‡๏ธ 26.666666666... // ๐Ÿ‘‡๏ธ 2 decimals const fixed = percentage.toFixed(2); console.log(fixed); // ๐Ÿ‘‰๏ธ "26.67"
The toFixed method formats the number to the provided number of digits after the decimal and rounds the number if necessary.

Note that the toFixed method returns a string, not a number.

If the number does not have any decimal places, it gets padded with zeros.

index.js
const percentage = (50 / 100) * 100; console.log(percentage); // ๐Ÿ‘‡๏ธ 50 // ๐Ÿ‘‡๏ธ 2 decimals const fixed = percentage.toFixed(2); console.log(fixed); // ๐Ÿ‘‰๏ธ "50.00"

Our second function shows how to get the percentage increase / decrease between two numbers.

index.js
function getPercentageIncrease(numA, numB) { return ((numA - numB) / numB) * 100; } // ๐Ÿ‘‡๏ธ `50` is 66.66% increase from `30` console.log(getPercentageIncrease(50, 30)); // ๐Ÿ‘‰๏ธ 66.666 // ๐Ÿ‘‡๏ธ `50` is 50% decrease from `100` console.log(getPercentageIncrease(50, 100)); // ๐Ÿ‘‰๏ธ -50

The first example shows that the percentage increase from 30 to 50 is 66.6666...%.

And the second shows, that the percentage increase from 100 to 50 is -50%.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee