COMisHARD
COMisHARD

Reputation: 923

Javascript: Check if a number is within n of another number

What is the cleanest way to check whether some variable X is within n numbers of some variable Z. n is an arbitrary defined number (i.e. 3).

So I want the

if (z {something} x){
    // run code if x and z are within 3 of each other
}

Upvotes: 0

Views: 62

Answers (2)

Preston Martin
Preston Martin

Reputation: 2973

Calculate the absolute value of the difference of z and x. http://www.w3schools.com/jsref/jsref_abs.asp

if ((Math.abs(z-x) <= 3){
    // do something
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386883

You could use the absolute difference of the value and check it.

if (Math.abs(x - z) < 3) { 

Upvotes: 2

Related Questions