2

What is the difference between:

    Dim a As Integer = CInt(2.2)

and

    Dim a As Integer = Math.Round(2.2)

?

AStopher
  • 3,668
  • 11
  • 50
  • 72
AlwaysLearning
  • 6,595
  • 3
  • 25
  • 55

2 Answers2

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
  • 372
  • 3
  • 13
-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
  • 3,668
  • 11
  • 50
  • 72
  • 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