User Tools

Site Tools


Constrain() function

Function to ensure a value exists within specific boundaries.

The following is a function for returning a numerical value constrained to a given range:


If the value is less than the lower limit, the lower limit will be returned. Likewise if the value is greater than the upper limit, the upper limit will be returned. If the value resides between the two, it will be returned intact.

A similar function exists in other languages but as shown below, it is easily fabricated using the inbuilt primitives of MMBasic.

As written below, it only works with integers. If your needs require it, adjust as necessary for Floats etc.





    Function Constrain(v As Integer,Llim As Integer, Ulim As Integer) As Integer
        Constrain=Min(Max(v,Llim ),Ulim )
    End Function

See also:

mmbasic/constrain_function.txt · Last modified: 2024/01/19 09:30 by