Reputation: 2696
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?
Upvotes: 16
Views: 34874
Reputation: 179
function calculatePercentageDifference(valueA, valueB) {
const difference = valueB - valueA;
const percentageDifference = Math.abs((difference / valueA) * 100);
return percentageDifference;
}
// Example values
const valueA = 50000;
const valueB = 80000;
const percentDiff = calculatePercentageDifference(valueA, valueB);
console.log(percentDiff); // Output: 60
Upvotes: 0
Reputation: 122916
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.
Upvotes: 38
Reputation: 355
in the case when we need to know the difference of some number to the etalon number:
function percDiff(etalon, example) {
return +Math.abs(100 - example / etalon * 100).toFixed(10);
}
// example
percDiff(11240, 11192); //=> 0.4270462633
percDiff(1000, 1500); //=> 50
percDiff(1000, 500); //=> 50
Upvotes: 1
Reputation: 31
diffPercent = function(a, b) {
return ( a<b ? "-" + ((b - a) * 100) / a : ((a - b) * 100) / b ) + "%";
}
Upvotes: 1