'Javascript: percentage difference between two values
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?
Solution 1:[1]
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
Solution 2:[2]
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
Solution 3:[3]
diffPercent = function(a, b) {
return ( a<b ? "-" + ((b - a) * 100) / a : ((a - b) * 100) / b ) + "%";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sergey |
Solution 3 | General Grievance |