10

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
srayner
  • 1,799
  • 4
  • 23
  • 39
  • FWIW, rounding upwards, and nearest are incompatible. You mean simply to round up. – David Heffernan Sep 22 '14 at 11:12
  • 3
    What should -4.4 round to? -5 or -4? – Lasse V. Karlsen Sep 22 '14 at 11:13
  • 2
    See http://docwiki.embarcadero.com/Libraries/XE6/en/System.Math.Ceil – Free Consulting Sep 22 '14 at 11:15
  • 2
    @AustinFrench Why not? Looks like rounding to me. Round to nearest is not the only way to round. You can round to nearest multiple of 10, round to 2dp, round up, round down, round towards zero, round away from zero. Lots of different forms of rounding exist. – David Heffernan Sep 22 '14 at 11:26
  • @DavidHeffernan OK, yes technically... It just seems "rounding" is such a generic and useless term when it is used in place of IMO more accurate phrases. For example 1 doesn't actually *round* anywhere. Maybe its just me. – Austin T French Sep 22 '14 at 11:44
  • @AustinFrench, thats because `1` is integer already. But suppose the rounding to 10¹ and here you are. – Free Consulting Sep 22 '14 at 11:57

2 Answers2

21

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()

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
-2
FindField('QTY').ASFLOAT := TRUNC(FindField('QTY').ASFLOAT) + 1

Works Fine

Markus
  • 2,265
  • 5
  • 28
  • 54
JEREMY
  • 1
  • 1
    Not so good on negative numbers and whole positive numbers. – LU RD Sep 07 '20 at 09:34
  • The question is simply mathematical - the database gymnastics are irrelevant and, as LU RD said, don't return the correct results required by the OP. – Dave Olson Sep 08 '20 at 19:06