2

What is the difference between:

    Dim a As Integer = CInt(2.2)

and

    Dim a As Integer = Math.Round(2.2)

?

AStopher
  • 4,207
  • 11
  • 50
  • 75
AlwaysLearning
  • 7,257
  • 4
  • 33
  • 68

3 Answers3

2

CInt returns an integer but will round the .5 to nearest even number so:

2 = CInt(2.5)
4 = CInt(3.5)

Are both true, which might not be what you want.

Math.Round can be told to round away from zero. But returns a double, so we still need to cast it

3 = CInt(Math.Round(2.5, MidpointRounding.AwayFromZero))
DontPanic345
  • 380
  • 3
  • 13
0

There is bigger differences in CInt(), Int() and Round()... and others. Round has parameters of rounding, so it is flexible and user friendly. But it do not change variable type. No "type conversion".

Meanwhile CInt() is a bit cryptic as it rounds too. And it is doing "Type conversion" to integer.

   2 = Int(2.555), 3 = CInt(2.555)
   2 = Int(2.5), 2 = CInt(2.5)

Some documentation states: When the fractional part of expression is exactly .5, CInt always rounds it to the nearest even number. For example, .5 rounds to 0, and 1.5 rounds to 2.

But I do not like that "exact 0.5", in real word it is "0.5000001"

So, doing integer math (like calculating bitmaps address Hi and Lo bytes) do not use CInt(). Use old school INT(). Until you get to negative numbers... see the fix() function.

If there is no need to convert type, use floor().

I think all this chaos of number conversion is for some sort of compatibility with some ancient software.

-1

The difference between those two functions is that they do totally different things:

  • CInt converts to an Integer type
  • Math.Round rounds the value to the nearest Integer

Math.Round in this instance will get you 2.0, as specified by the MSDN documentation. You are also using the function incorrectly, see the MSDN link above.

Both will raise an Exception if conversion fails, you can use Try..Catch for this.

Side note: You're new to VB.NET, but you might want to try switching to C#. I find that it is a hybrid of VB.NET & C++ and it will be far easier for you to work with than VB.NET.

Community
  • 1
  • 1
AStopher
  • 4,207
  • 11
  • 50
  • 75
  • 1
    'Hybrid' indeed. C# is essentially VB with braces,semicolons and the vagaries of C. This is borne out by http://converter.telerik.com/ and http://www.literateprogramming.com/ctraps.pdf is an instructive read (since you mention it, C++ has aptly been described as an octopus made by nailing extra legs onto a dog) >;-). As a beginner, he would be well advised to start with VB, which has less insiduous traps. P.S. I'm not spoiling for a language war, just offering a different opinion. – smirkingman Dec 03 '19 at 10:46
  • According to the documentation you link in this answer `Math.Round` returns a `Decimal` type, or `Double` type depending on how it is called. – HackSlash Jan 06 '21 at 22:59