Java - limit number between min and max

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.


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


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.


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