I am using the following javascript code to display the difference in percentage between two values.
A = 11192; B = 10474; percDiff = (vars.A - vars.B) / vars.B * 100;
Which gives: 6.855069696391064
Then
if (percDiff > 20) { //dosomething } else { //dosomething }
The problem is:
If value B is higher than value A then i get a NaN, for instance;
How can I overcome this issue? I thought about using Math.abs()
Any suggestions?
Advertisement
Answer
I think you can use this formula to determine the relative difference (percentage) between 2 values:
var percDiff = 100 * Math.abs( (A - B) / ( (A+B)/2 ) );
Here’s a utility method:
function relDiff(a, b) { return 100 * Math.abs( ( a - b ) / ( (a+b)/2 ) ); } // example relDiff(11240, 11192); //=> 0.42796005706134094
Note for people thinking the answer provides a wrong result: this question/answer concerns percentage difference1, not percentage change2.
Here’s a snippet to demonstrate the difference (pun intended;)
const relativePercentageDifference = (a, b) => Math.abs( ( ( a - b ) / ( ( a + b ) / 2 ) ) * 100 ); const percentageChange = (a, b) => ( b / a * 100 ) - 100; console.log(`relative % difference 2000 - 1000: ${ relativePercentageDifference(2000, 1000).toFixed(2)}%`); console.log(`% change 2000 - 1000: ${ percentageChange(2000, 1000).toFixed(2)}%`); console.log(`relative % difference 1000 - 2000: ${ relativePercentageDifference(1000, 2000).toFixed(2)}%`); console.log(`% change 1000 - 2000: ${ percentageChange(1000, 2000).toFixed(2)}%`);
1 The percentual difference between two values divided by the average of the two values.
2 The percentual difference (in-/decrease) between two numbers divided by the original number.