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.)
A clamp is a fastening device used to hold or secure objects tightly together to prevent movement or separation through the application of inward pressure.
math. clamp() restricts a certain number x between a min number and a max number. Alright, thanks very much I understand it now! The function takes x , min and max arguments and it returns the clamped value.
You could write an extension method:
public static T Clamp<T>(this T val, T min, T max) where T : IComparable<T> { if (val.CompareTo(min) < 0) return min; else if(val.CompareTo(max) > 0) return max; else return val; }
Extension methods go in static classes - since this is quite a low-level function, it should probably go in some core namespace in your project. You can then use the method in any code file that contains a using directive for the namespace e.g.
using Core.ExtensionMethods int i = 4.Clamp(1, 3);
Starting with .NET Core 2.0 System.Math
now has a Clamp
method that can be used instead:
using System; int i = Math.Clamp(4, 1, 3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With