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
There isn't one, but it's not too hard to make one. I found one here: clamp
It is:
public static T Clamp(T value, T max, T min)
where T : System.IComparable {
T result = value;
if (value.CompareTo(max) > 0)
result = max;
if (value.CompareTo(min) < 0)
result = min;
return result;
}
And it can be used like:
int i = Clamp(12, 10, 0); -> i == 10
double d = Clamp(4.5, 10.0, 0.0); -> d == 4.5