Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - limit number between min and max

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)

like image 512
Sean Connolly Avatar asked Jul 29 '13 20:07

Sean Connolly


People also ask

Which value is any number between minimum and maximum?

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).

How do you limit integers in Java?

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 ).

Is there a min and max function in Java?

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.


1 Answers

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

like image 86
Barry Staes Avatar answered Sep 20 '22 06:09

Barry Staes