How to calculate difference in percentage using JavaScript
There can be many scenarios where you want to get the difference in percentage between two numbers. In real life, it could be perhaps comparing the difference in size of two companies, a financial difference between the two companies or maybe difference in winnings between you and your friends favourite football team.
NOTE: Percentage difference, should not be confused with percentage change
Formula
The formula for calculating the difference in percentage is as follows:
Diff = 100 × |a - b| / ((a + b) / 2)
Let's do it in code
const getPercentageDiff = (a, b) => { const numerator = a - b; const denominator = (a + b) / 2; const diff = 100 * (numerator / denominator); return (diff < 0 ? diff * -1 : diff).toFixed(2); };
We first calculate the numerator, |a-b|. Then the denominator, ((a + b) / 2). Then we multiply them with 100. And then it looks a little bit funny.. To explain, it does not matter if the values is a or b in order to get the same percentage diff. Huh? - So, if a = 100, and b = 200 it is the same as if a = 200 and b = 100. Therefore, we sometimes can get a negative result.
a = 100, b = 200 Result = -67.67% a = 200, b = 100 Result = 67.67%
So in order to make the function a little bit more user friendly, we transform the negative number to a positive number instead. Again, this is not the same as percentage change where it does matter which value is a and b.
Let's try it out
console.log(getPercentageDiff(100, 200)); // 66.67% console.log(getPercentageDiff(200, 100)); // 66.67% console.log(getPercentageDiff(60, 75)); // 22.22% console.log(getPercentageDiff(600, 25)); // 184%
Outro
In todays guide, we showed how to calculate the difference in percentage between two numbers. To get the percentage change, you can see this guide.