User Tools

Site Tools


mmbasic:constrain_function

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:

lowerlimit<=n<=UpperLimit

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.

Syntax:

=Constrain(TestValue,LowerLimit,UpperLimit)

Example:

x=Constrain(TriggerTemp,7,10)

    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 127.0.0.1