Java - limit number between min and max

2019-01-19 10:03发布

问题:

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)

回答1:

As of version 21, Guava includes Ints.constrainToRange() (and equivalent methods for the other primitives). From the release notes:

added constrainToRange([type] value, [type] min, [type] max) methods which constrain the given value to the closed range defined by the min and max values. They return the value itself if it's within the range, the min if it's below the range and the max if it's above the range.

Copied from https://stackoverflow.com/a/42968254/122441 by @dimo414.

Unfortunately this version is quite recent as of July 2017, and in some projects (see https://stackoverflow.com/a/40691831/122441) Guava had broken backwards compatibility that required me to stay on version 19 for now. I'm also shocked that neither Commons Lang nor Commons Math has it! :(



回答2:

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



回答3:

The Math.max(int a, int b) function is defined as:

public static int min(int a, int b) {
    return (a <= b) ? a : b;
}

So you can make a combination of the max and min functions as follows:

private static int MAX=10;
private static int MIN=0;

public int limit(int a) {
    return (a > MAX) ? MAX : (a < MIN ? MIN: a );
}


回答4:

Generic method for any class implementing Comparable (including Number and its sub-classes):

public static <T extends Comparable<? super T>> T limit(T o, T min, T max){
    if (o.compareTo(min) < 0) return min;
    if (o.compareTo(max) > 0) return max;
    return o;
}

The only requirement is that all arguments must be of the same class. It prevents possible type conversion loss. In fact it is incorrect to compare float with double of long with int etc. For example (double) 0.1 != (float) 0.1.

Usage:

double x = 13.000000001;
x = limit(x, 12.0, 13.0);
System.out.println("x = " + x); //x = 13.0

Unfortunately it is impossible to change the first argument directly by just limit(x, 12.0, 13.0) because primitive types are immutable.



回答5:

If you're on Android, use the MathUtils (in support library), it has only one function which specifically does this called clamp.

This method takes a numerical value and ensures it fits in a given numerical range. If the number is smaller than the minimum required by the range, then the minimum of the range will be returned. If the number is higher than the maximum allowed by the range then the maximum of the range will be returned.



回答6:

You do not need an external library for this, try this test case:

public class RandomNumber {
public static void main(String[] Args) {
    System.out.println("random = " + randomInRange(5,10));
}

public static double randomInRange(double arg1, double arg2) {
    double my_number = Math.ceil(Math.random() * (arg1 - arg2) + arg2);
    return my_number;
 }

}