Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more compact way of checking if a number is within a range?

I want to be able to test whether a value is within a number range. This is my current code:

if ((year < 2099) && (year > 1990)){
    return 'good stuff';
}

Is there a simpler way to do this? For example, is there something like this?

if (1990 < year < 2099){
    return 'good stuff';
}
like image 915
Inigo Avatar asked Dec 10 '10 12:12

Inigo


People also ask

How do you check if number is within a range?

If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.

How do you check if a value is within a range in Javascript?

const inRange = (num, num1, num2) => Math. min(num1, num2) <= num && Math. max(num1, num2) >= num; Could be like this if you want to make inRange inclusive and not depend on order of range numbers (num1, num2).


1 Answers

In many languages, the second way will be evaluated from left to right incorrectly with regard to what you want.

In C, for instance, 1990 < year will evaluate to 0 or 1, which then becomes 1 < 2099, which is always true, of course.

Javascript is a quite similar to C: 1990 < year returns true or false, and those boolean expressions seem to numerically compare equal to 0 and 1 respectively.

But in C#, it won't even compile, giving you the error:

error CS0019: Operator '<' cannot be applied to operands of type 'bool' and 'int'

You get a similar error from Ruby, while Haskell tells you that you cannot use < twice in the same infix expression.

Off the top of my head, Python is the only language that I'm sure handles the "between" setup that way:

>>> year = 5
>>> 1990 < year < 2099
False
>>> year = 2000
>>> 1990 < year < 2099
True

The bottom line is that the first way (x < y && y < z) is always your safest bet.

like image 110
Mark Rushakoff Avatar answered Nov 11 '22 19:11

Mark Rushakoff