Check if a value is within a range of numbers

Sotiris picture Sotiris · Jun 23, 2011 · Viewed 256.6k times · Source

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.

Answer

Pointy picture Pointy · Jun 23, 2011

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
}