I would like to clamp a value x
to a range [a, b]
:
x = (x < a) ? a : ((x > b) ? b : x);
This is quite basic. But I do not see a function "clamp" in the class library - at least not in System.Math
.
(For the unaware to "clamp" a value is to make sure that it lies between some maximum and minimum values. If it’s greater than the max value, then it’s replaced by the max, etc.)