Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: percentage difference between two values

Tags:

javascript

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; NaN

How can I overcome this issue? I thought about using Math.abs()

Any suggestions?

like image 434
David Garcia Avatar asked May 20 '14 12:05

David Garcia


2 Answers

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

like image 112
KooiInc Avatar answered Sep 24 '22 10:09

KooiInc


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
like image 24
Sergey Avatar answered Sep 23 '22 10:09

Sergey