Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check whether the number is nearly equal javascript

Tags:

javascript

I want to know whether it is possible?

Let Suppose:

var a = 2592;
var b = 2584;
if(a nearly equal to b) {
// do something
}
like image 393
Muhammad Talha Akbar Avatar asked Jan 29 '13 11:01

Muhammad Talha Akbar


2 Answers

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.

like image 140
jAndy Avatar answered Nov 04 '22 17:11

jAndy


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 image 28
The Software Barbarian Avatar answered Nov 04 '22 18:11

The Software Barbarian