How to limit a number to a range
Short answer
Since Java 21 there is Math.clamp(value, min, max):
void main() {
IO.println(Math.clamp(150, 0, 100));
IO.println(Math.clamp(-5, 0, 100));
IO.println(Math.clamp(42, 0, 100));
}Output:
100
0
42With min and max
The combination of Math.min() and Math.max() gives the same result — this is how it is done in older Java versions:
void main() {
int volume = 120;
int limited = Math.max(0, Math.min(volume, 100));
IO.println(limited);
}Output:
100Decimals
clamp() works with double too:
void main() {
double opacity = 1.4;
IO.println(Math.clamp(opacity, 0.0, 1.0));
}Output:
1.0Common mistake
Mixing up the order of the bounds. Math.clamp() checks that the minimum is not greater than the maximum and throws:
void main() {
IO.println(Math.clamp(50, 100, 0));
}Output:
Exception in thread "main" java.lang.IllegalArgumentException: 100 > 0Functions used in this recipe
- Math.min() — Returns the smaller of two numbers.
- Math.max() — Returns the larger of two numbers.