Jef Null
Jef Null

Reputation: 415

Detect if a number is between 2 others?

What's the best way to detect if a number, is between two other numbers? Is there already a function to do this in the Math object?

Upvotes: 1

Views: 417

Answers (5)

George Cummins
George Cummins

Reputation: 28936

There is no specific function, but you can do it like this:

lowNumber < yourNumber && yourNumber < highNumber

Upvotes: 9

JFFF
JFFF

Reputation: 989

if ( yournumber < highNumber && yournumber > lowNumber ){    
  // do something    
} else {    
  // do something else    
}

Upvotes: 1

Corey Ogburn
Corey Ogburn

Reputation: 24769

The only optimized way to do this is to guess which is more likely: Is the number your checking more likely to be lower than the lower bound, or is it more likely to be higher than the upper bound?

With this in mind, you can take advantage of short circuiting by placing the more likely failure check first (if it fails that, it won't test the less likely criteria). This is the only way to optimize it.

Even this will save you the smallest amount of time that is most likely not going to be noticed. Perhaps if you were making this check millions of times, you might save a fraction of a second over the alternative.

Upvotes: 0

user113716
user113716

Reputation: 322622

Though the code solution is fairly obvious, if you're going to use it a lot, you may want to implement it on Number.prototype for convenience:

Number.prototype.inRange = function( a,b ) {
    var n = +this;
    return ( n > a && n < b );
};

So you'd use it like this:

(5).inRange( 3, 7 ); // true

Example: http://jsfiddle.net/dTHQ3/

Upvotes: 3

t3rse
t3rse

Reputation: 10124

Um if it is greater than one and less than the other.

var num1 = 3;
var num2 = 5;
var x = 4;
var isBetween = (num1 < x && num2 > x);

Upvotes: 2

Related Questions