check whether the number is nearly equal javascript

Here's the old school way to do it...

approxeq = function(v1, v2, epsilon) {
  if (epsilon == null) {
    epsilon = 0.001;
  }
  return Math.abs(v1 - v2) < epsilon;
};

so,

approxeq(5,5.000001)

is true, while

approxeq(5,5.1)

is false.

You can adjust pass in epsilons explicitly to suit your needs. One part in a thousand usually covers my javascript roundoff issues.


Like so.

var diff = Math.abs( a - b );

if( diff > 50 ) {
    console.log('diff greater than 50');
}

That would compare if the absolute difference is greater than 50 using Math.abs and simple comparison.


One line Es6 way version of The Software Barbarian:

const approxeq = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) <= epsilon;

console.log(approxeq(3.33333, 3.33322)); // true
console.log(approxeq(2.3, 2.33322)); // false
console.log(approxeq(3, 4, 1)); // true

I changed it to include the number in the margin. So with an epsilon margin of 1 approxeq between 1 and 2 is true


var ratio = 0;
if ( a > b) {
   ratio = b / a;
}
else {
    ratio = a / b;
}
if (ratio > 0.90) {
    //do something
}

Tags:

Javascript