Java - limit number between min and max

后端 未结 7 708
耶瑟儿~
耶瑟儿~ 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

提交回复
热议问题