DnR DnR - 2 months ago 9
Vb.net Question

Integer value rounding in VB.NET

I have code as below:

Dim num1 As Integer
Dim num2 As Integer

num1 = 12.5
num2 = 17.5


When I output the values, I get this:

num1: 12
num2: 18


If
12.5
become
12
, is
17.5
supposed to be
17
?

Or if
17.5
become
18
, is
12.5
supposed to be
13
?

I'm pretty new in Visual Basic, and it's hard to find any reference on this.

Answer

This is because VB use banker’s rounding (round-to-even rule) as stated in Integer documentation

In this method, when the remainder at the rounding position is .5, that number is rounded up when the number before it is odd, and rounded down when the number before it is even.

For example, using round-to-even rule

2.5 round down to the even number 2.0, 
3.5 would round up to the even number 4.0
Comments