October 17, 2009

VBScript Ceil and Floor Functions

VBScript does not have native Ceiling and Floor functions. In order to use these function in your financial or mathematical applications, you will have to write your own VBScript implementation. By definition:

The ceiling and floor functions map a real number to the next largest or next smallest integer. More precisely, ceiling(x) is the smallest integer not less than x and floor(x) is the largest integer not greater than x.

So here is the VBScript implementation of these two functions:

Function Ceil(Number)

    Ceil = -Int(-Number)

End Function

Function Floor(Number)

    Floor = Int(Number)

End Function

Ceil Function Output

Ceil(99.99999999) = 100
Ceil(99) = 99
Ceil(1.99999999) = 2
Ceil(1) = 1
Ceil(0.99999999) = 1
Ceil(0) = 0
Ceil(-0.99999999) = -0
Ceil(-1) = -1
Ceil(-1.99999999) = -1
Ceil(-99) = -99
Ceil(-99.99999999) = -99

Floor Function Output

Floor(99.99999999) = 99
Floor(99) = 99
Floor(1.99999999) = 1
Floor(1) = 1
Floor(0.99999999) = 0
Floor(0) = 0
Floor(-0.99999999) = -1
Floor(-1) = -1
Floor(-1.99999999) = -2
Floor(-99) = -99
Floor(-99.99999999) = -100

Explanation: mathematical Floor is rounding the number towards negative infinity. The VBA/VBScript Int() function behaves exactly like that. And for mathematical Ceiling, which is rounding towards positive infinity, use the same function but change the sign of its input and output.