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?
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
See also...
JsFiddle
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With