Java - limit number between min and max

后端 未结 7 705
耶瑟儿~
耶瑟儿~ 2020-12-06 08:53

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

相关标签:
7条回答
  • 2020-12-06 09:25

    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

    0 讨论(0)
  • 2020-12-06 09:27

    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.

    0 讨论(0)
  • 2020-12-06 09:27

    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.

    0 讨论(0)
  • 2020-12-06 09:29

    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! :(

    0 讨论(0)
  • 2020-12-06 09:29

    I understand this was asked for Java. In Android world, it's common to use Kotlin and Java combined. In case some Kotlin user reached here (just like me), then they can use coerceIn extension function:

    Kotlin Code:

    println(10.coerceIn(1, 100)) // 10
    println(10.coerceIn(1..100)) // 10
    println(0.coerceIn(1, 100)) // 1
    println(500.coerceIn(1, 100)) // 100
    

    Read more on official Kotlin Documentation.

    0 讨论(0)
  • 2020-12-06 09:30

    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;
     }
    

    }

    0 讨论(0)
提交回复
热议问题