Check if a value is within a range of numbers
I want to check if a value is in an accepted range. If yes, to do something; otherwise, something else.
The range is 0.001-0.009
. I know how to use multiple if
to check this, but I want to know if there is any way to check it in a single if
statement.
Solution 1:
You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if
" statements to do it, either:
if (x >= 0.001 && x <= 0.009) {
// something
}
You could write yourself a "between()" function:
function between(x, min, max) {
return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
// something
}
Solution 2:
Here is an option with only a single comparison.
// return true if in range, otherwise false
function inRange(x, min, max) {
return ((x-min)*(x-max) <= 0);
}
console.log(inRange(5, 1, 10)); // true
console.log(inRange(-5, 1, 10)); // false
console.log(inRange(20, 1, 10)); // false