Java - limit number between min and max

Sean Connolly picture Sean Connolly · Jul 29, 2013 · Viewed 48.5k times · Source

I want to return the number as long as it falls within a limit, else return the maximum or minimum value of the limit. I can do this with a combination of Math.min and Math.max.

public int limit(int value) {
    return Math.max(0, Math.min(value, 10));
}

I'm wondering if there's an existing limit or range function I'm overlooking.
3rd party libraries welcome if they are pretty common (eg: Commons or Guava)

Answer

Barry Staes picture Barry Staes · Mar 31, 2014

OP asks for this implementation in a standard library:

int ensureRange(int value, int min, int max) {
   return Math.min(Math.max(value, min), max);
}

boolean inRange(int value, int min, int max) {
   return (value>= min) && (value<= max);
}

A pity the standard Math library lacks these