6

I want to perform integer division in VB.NET, i.e. only keep the whole part of division result.

Dim a, b, c as int32
a = 3500
b = 1200
c = a/b

This example outputs 3.

How do I make it return 2 instead?

Victor Zakharov
  • 24,856
  • 17
  • 77
  • 143
Gopal
  • 11,346
  • 52
  • 146
  • 227

2 Answers2

18

Since this is Visual Basic you have 2 division operators / which is for Standard division and \ which is used for integer division, which returns the "integer quotient of the two operands, with the remainder discarded" which sounds like what you want.

results:

a/b = 3
a\b = 2
Mark Hall
  • 52,990
  • 9
  • 92
  • 107
  • Much better than using a `Math.Floor`, since we are talking VB.NET here. – Victor Zakharov Oct 17 '12 at 20:30
  • +1 for nice feature. But using `/` or `\\` wont be much readable and wont show intention of rounding up the values in the calculation. – Parag Meshram Oct 17 '12 at 21:09
  • @MarkHall - I have learned C# & VB.NET w/out prior knowledge to VB6. And I am new to VB.NET so this feature is a surprise for me :) – Parag Meshram Oct 17 '12 at 21:15
  • @ParagMeshram It is one I constantly bump my head against trying to remember which is which. I do agree that having a nicely named function is clearer :). Commenting is your friend – Mark Hall Oct 17 '12 at 21:17
4

Actual calculation: 3500/1200 = 2.916

You have to use Math.Floor method to roundup the value to 2 as below -

c = Math.Floor(a/b)

More information is available on MSDN - Math.Floor

Parag Meshram
  • 7,930
  • 9
  • 48
  • 87
  • 3
    This is wrong if negative numbers are involved (https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division) you have to round towards zero. – wischi Jul 05 '17 at 10:23