How to determine the direction of rounding when converting to an integer in visual base

I am trying to reproduce some Visual Basic code in python. I have a function that produces a fraction (double) and converts it to an integer like this:

Dim random_int As Integer
Dim rounded_int As Integer
random_int = CInt(Math.Ceiling(Rnd() * n)) + 1
rounded_int = CInt(random_int/2)

      

CInt()

rounds double values ​​to the nearest integer. However, when the value is 0.5, it seems random; sometimes up, sometimes down. This makes it difficult to verify the code. In python (2.7), a number is always rounded in one direction.

I could add or subtract a small number to the result (like 0.1), but the original code shouldn't change.

Is this behavior normal or can I control it in some way?

+3


source to share


1 answer


CInt

in VBA uses Rounding Banker , also called "half to even". This explains the "random" behavior. Here are some examples:

2.5 -> 2
3.5 -> 4

      

You cannot customize the behavior with CInt

. Historically, implementations of rounding methods have been inconsistent between various Microsoft technologies, this KB article illustrates this and provides code examples for various other common forms of rounding.



Another addition: Due to technical limitations, floating point 1.5

can be represented 1.4999999

internally, which causes even more confusion. This article tries to explain why this is happening and how to fix it.

Edit . I assumed Visual Basic for Applications because of the tag vba

, if you are using Visual Basic.NET you can call Math.Round

with overload MidpointRounding

.

+1


source







All Articles