Check if a value is within a range of numbers
If you must use a regexp (and really, you shouldn't!) this will work:
/^0\.00([1-8]\d*|90*)$/
should work, i.e.
^
nothing before,- followed by
0.00
(nb: backslash escape for the.
character) - followed by 1 through 8, and any number of additional digits
- or 9, followed by any number of zeroes
$
: followed by nothing else
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
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
}