Rounding a number up to a Ceiling
In this lesson we will see how to write a custom function that gives the ceiling of a number.
You can download the stack for this lesson here: https://tinyurl.com/y7ebh6ez
Update Note: In LiveCode 7.1 onwards, LiveCode has its own built-in "ceiling()" function. As such, the following lesson applies only to LiveCode versions earlier than 7.1.
Our custom function
We are going to write the function
The function returns the ceiling of the given parameter pNumber. The ceiling of a number is the smallest following integer, more precisely ceiling(x) is the smallest integer not less than x.
The function will be called with a statement such as one of the following.
put ceiling(it) into field "Total Price" if ceiling(field "Incident") > 4 then go next card
Our example stack
For this lesson all we need is an entry field and a button to call the ceiling function and return the result.
The ceiling function
The first thing the custom function must do is check that it has been passed a number, if the pNumber parameter passed to the function is not a number the function will return an error message.
The function's purpose is to produce the next higher number, or to "round up". We can't use the round function for this, because the round function rounds to the nearest integer, not necessarily to the next higher
round(2.4) is 2, rather than 3
However, if we truncate the number(to get its integer part) and then add 1, we do get the desired result. By truncating 2.4 we get 2, add 1 and we get 3, the desired result.
Are we done? Not quite: there are two cases where this formula does not produce the ceiling number.
1 - If the number is already an integer, it is its own ceiling, so we don't want to add 1 to it.
2 - if the number is negative and not an integer, the above doesn't give us the ceiling. For example, the ceiling of -3.6 is -3, but truncating -3.6 gives -3, adding 1 gives us -2.
In both these cases the truncating gives us the ceiling of the number, without having to add 1.
The trunc function
Luckily for us LiveCode has a built in trunc function which returns the integer part of a number so we can use it in our custom function.
trunc(33.567) -- returns 33
trunc(-6.3) -- returns -6
The script of the ceiling function
function ceiling pNumber ## Check we have been passed a number if pNumber is not a number then return "Error: not a number" end if ## Check if the number is already an integer or is negative if pNumber < zero or pNumber is an integer then ## truncating gives the ceiling return trunc(pNumber) else ## truncate the number and add 1 to get the ceiling return trunc(pNumber) + 1 end if end ceiling