Date/Time Początkujący

Clamp a value between bounds with a single clear call.

✕ Java 8
// Clamp value between min and max
int clamped =
    Math.min(Math.max(value, 0), 100);
// or: min and max order confusion
✓ Java 21+
int clamped =
    Math.clamp(value, 0, 100);
// value constrained to [0, 100]
Widzisz problem z tym kodem? Daj nam znać.
📖

Self-documenting

clamp(value, min, max) is unambiguous.

🛡️

Less error-prone

No more swapping min/max order by accident.

🎯

All numeric types

Works with int, long, float, and double.

Stare podejście
Nested min/max
Nowoczesne podejście
Math.clamp()
Od JDK
21
Poziom trudności
Początkujący
Math.clamp()
Dostępne

Widely available since JDK 21 LTS (Sept 2023)

Math.clamp(value, min, max) constrains a value to the range [min, max]. Clearer than nested Math.min/Math.max and available for int, long, float, and double.

Udostępnij 𝕏 🦋 in