# Tip : Clamp a value to a Range

I have a situation where I need a value to be in a specific range, regardless of what value is provided… The Upper value limit may be set to -1 (indicated no limit)

``new_value=Max(0,Min(old_value,If(maxLimit>0,maxLimit,old_value)))``

If maxLimit is -1 then the value is clamped to the range of Zero to “anything”
if maxLimit is anything else if new_value will be forced to be Zero to MaxLimit

of course the Max(0 portion could also be expanded to allow fully custom ranges, but for my app it needed only positive values

This is much shorter than

``````new_value=old_value
if new_value<0 then
new_value=0
elseif new_value>maxLimit and maxLimit>0 then
new_value=maxLimit``````

just a tip to perhaps spark an idea on changing something you may have thought to be too verbose

Neat tip Dave,
In some other languages there’s even a clamp function.

``value = clamp( value, minValue, maxValue )``

Wouldn’t this be simpler?

``new_value = max(min(test, max_value), min_value)``

Or perhaps I didn’t fully understand…

EDIT:
yeah I see you have an unlimited option. But if you handle integer, it would suffice to set the maxValue to &hFFFFFFFF

If speed is your concern (like millions of clamps) the last time I tested this the longer code version (if v < minval then v = minval…) is significantly faster than using Min() Max().

This is clearly a case where it’s more readable as a proper function, but much faster as code - it would be nice if there was an #inline pragma like C has. Turns out there’s a feature request from 2002 on this: <https://xojo.com/issue/3712>

Remember #inline is a HINT not a REQUIREMENT
http://en.wikipedia.org/wiki/Inline_function#Problems