How do I round a positive float up the next integer?

srayner picture srayner · Sep 22, 2014 · Viewed 11.2k times · Source

I need to round a positive float upwards to the nearest integer.

examples;

1.0 rounds up to 1    
2.1 rounds up to 3
3.5 rounds up to 4
4.9 rounds up to 5 

i.e. always round up.

Answer

David Heffernan picture David Heffernan · Sep 22, 2014

Use the Ceil function from the Math unit. From the documentation:

Rounds variables up toward positive infinity.

Call Ceil (as in ceiling) to obtain the lowest integer greater than or equal to X. The absolute value of X must be less than MaxInt. For example:

  • Ceil(-2.8) = -2
  • Ceil(2.8) = 3
  • Ceil(-1.0) = -1

I cannot tell whether or not the behaviour of Ceil meets your expectations for negative input values, because you did not specify what to do there. However, if Ceil does not meet your expectations, it is easy enough to write a function to meet your needs, by combining Abs() and Ceil()