C# Reference ยท Numbers and Math
C# Math.Clamp() method
Reference for C# Math.Clamp(): restrict a number to a minimum and maximum, see which types have overloads, and learn how NaN and bad ranges behave.
Math.Clamp(value, min, max) forces a number into a closed range. If value is below min, you get min. If it is above max, you get max. Otherwise you get value unchanged. It replaces the common but error-prone Math.Min(max, Math.Max(min, value)) pattern with one readable call.
Overloads exist for every built-in numeric type: byte, sbyte, short, ushort, int, uint, long, ulong, nint, nuint, float, double and decimal. Since .NET 7 the same operation is also available on the number types themselves (int.Clamp(...)) through generic math.
int volume = Math.Clamp(135, 0, 100); // 100 double ratio = Math.Clamp(-0.2, 0.0, 1.0); // 0
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static int Math.Clamp(int value, int min, int max) public static double Math.Clamp(double value, double min, double max) public static decimal Math.Clamp(decimal value, decimal min, decimal max) // ... and the same shape for the other numeric types public static T T.Clamp(T value, T min, T max) // generic math (INumber<T>)
| Name | Description |
|---|---|
value |
The number to limit. |
min |
The lower bound (inclusive). |
max |
The upper bound (inclusive). |
Returns: min if value < min, max if value > max, otherwise value. The return type is the same as the argument type.
Errors: throws ArgumentException when min > max. min == max is allowed and always returns that value.
Usage notes
- All three arguments must be the same type. Mixing
intanddoublepicks thedoubleoverload through implicit conversion, which is usually what you want, but alongvalue withintbounds returns along. - NaN passes through. For
floatanddouble, aNaNinput is returned asNaN. Test withdouble.IsNaNfirst if that is not acceptable. - The bounds are inclusive.
Math.Clamp(10, 0, 10)returns10. - Clamping is not wrapping. To loop a value back to the start of a range (an angle, a carousel index), use the remainder operator instead.
- Not for dates.
Math.Clamponly covers numeric types. ForDateTime,TimeSpanor your own types, write a small helper built onCompareTo(the genericT.Clampworks only for number types). - Fast. The method is a pair of comparisons and is inlined by the JIT. Prefer it to hand-written conditionals for clarity.
- Validate bounds once. If
minandmaxcome from configuration, check them when you load the configuration. A bad range then fails early instead of inside a hot loop.
Related
num-minmaxandnum-abs-signnum-mathfor the wholeMathclassnum-generic-math- Tutorial: Math and numbers