roundUp function?

Quentin Long cubist at aol.com
Thu Nov 24 04:31:22 EST 2016


sez Roger Eller <roger.e.eller at sealedair.com>:
> We have round, which will either round up or down depending on the decimal
> value being > or < .5, but what if I want ANY decimal value, even .01 to
> round UP to the next whole number?
The best solution is the Ceiling function. Since that's not an option for the version of LiveCode you're working with, you gotta roll your own.

The proposed "return int (DerNumber +.5)" solution won't do, because any number whose decimal part is *less than* .5 will round down to the integer part. Instead, what you want is something like this:

if DerNumber = int (DerNumber) then -- DerNumber doesn't *have* a decimal part
  return DerNumber
else -- DerNumber *does* have a decimal part, hence rounds up
  return int (DerNumber) + 1
end if

That works fine for positive numbers and zero. Negative numbers, not so much. So, a tweak to handle negative numbers:

if DerNumber = int (DerNumber) then -- DerNumber doesn't *have* a decimal part
  return DerNumber
else -- DerNumber *does* have a decimal part, hence rounds up
  return int (DerNumber) + (DerNumber / abs (DerNumber))
end if

The expression "DerNumber / abs (DerNumber)" yields a value of +1 when DerNumber is a positive number, and -1 when DerNumber is negative. Alas, it runs into problems when DerNumber is zero. So, tweaking again:

function CeilingOf DerNumber
  if DerNumber = 0 then
    return 0
  else
    if DerNumber = int (DerNumber) then -- DerNumber doesn't *have* a decimal part
      return DerNumber
    else -- DerNumber *does* have a decimal part, hence rounds up
      return 1 + int (DerNumber)
    end if
  end if
end CeilingOf

Please don't feed a non-number to this function. It won't like that.
 
"Bewitched" + "Charlie's Angels" - Charlie = "At Arm's Length"
    
Read the webcomic at [ http://www.atarmslength.net ]!
    
If you like "At Arm's Length", support it at [ http://www.patreon.com/DarkwingDude ].




More information about the use-livecode mailing list