VB.NET integer rounding division

When two variables are declared as integers and you execute

14/4, you get 4, but when you use integer division, 14 \ 4, you get 3.

I thought when you use integer division, it rounds to the nearest even number. So 14 \ 4 = 3.5 (4 is the closest even number) should be 4, right?

+7
source share
2 answers

When you pass a floating point number to an integer in VB.NET, the value is rounded to the nearest even number. Apparently rounding a number when converting it to an integer is a behavior that extends to days of the BASIC language.

However, when performing integer division (with the \ operator), the fractional part is simply discarded, regardless of which fractional part. That is why you get the behavior you see.

+7
source

In VB.NET, the / operator is defined to return a floating point result. It converts the variables to double before doing the division.

This does not apply to integer division \ , where division is performed without a remainder if the quotient is decimal (decimal places are ignored). For example, if the factor is 3.x , then x ignored.

+10
source

All Articles