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)

    if Ceil <> Number then

        Ceil = Ceil + 1

    end if

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

Surprisingly, I found out that the VBScript Int() function behaves exactly like a Floor function. Therefore, I have tried not to re-invent the wheel.