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)
The range is a numerical indication of the span of our data. To calculate a range, simply subtract the min (13) from the max (110).
There is no way to limit a primitive in Java. The only thing you can do is to write a wrapper class for this. Of course by doing this you lose the nice operator support and have to use methods (like BigInteger ).
Collections. min() method return the minimum element in the specified collection and Collections. max () returns the maximum element in the specified collection, according to the natural ordering of its elements.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With