3

I don't want use old Visual Basic methods in my code, and I'm confused about what's the newest VB.NET method corresponding to the old CInt() Visual Basic method.

For example,

Dim n1 as Double : n1 = CInt(2.1111111) 'Gets only 2 without rounding it
Dim n2 as Double : n2 = CInt(2.7777777) 'Get only 2 without rounding it
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Max
  • 4,965
  • 17
  • 49
  • 64
  • I don't want to round the value, but only truncate it by its decimal value as CInt() method. – Max Jun 15 '12 at 16:55
  • 2
    CInt in VB6 performed rounding as well - see: http://www.chennaiiq.com/developers/reference/visual_basic/functions/cint.asp – Reed Copsey Jun 15 '12 at 16:55

1 Answers1

9

You can use CInt in VB.NET as well. It is a standard type conversion function supported by the VB.NET compiler. There is no reason to avoid it.

However, nearly every type conversion operation will round to the nearest integer (including other methods such as Convert.ToInt32, etc.), not truncate. You can force a truncation by using Int or Fix (which have different behaviors for negative numbers).

Note that, you can do the same as Int/Fix by using Math.Truncate and Math.Floor, should you wish to avoid the VB.NET specific conversion routines.


On a side note - CInt in Visual Basic 6.0 also performed rounding. The behavior in VB.NET for CInt is the same as in Visual Basic 6.0.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • +1 Just use CInt. [There's no reason to avoid it](http://stackoverflow.com/questions/226517/is-the-microsoft-visualbasic-namespace-true-net-code). It is a [fully supported](http://msdn.microsoft.com/en-us/library/aa289509.aspx#vbtchmicrosoftvisualbasicnetinternalsanchor4) part of the .Net framework. Use CInt, move on, and get some actual work done. – MarkJ Jun 15 '12 at 17:01
  • 1
    @MarkJ I agree - if you're going to write in Visual Basic, you might as well *use* the tools provided by the language. It's kind of like saying "I want to avoid using int in C#, and am going to always write `System.Int32` because that's how the framework defines it"... – Reed Copsey Jun 15 '12 at 17:03
  • Ah, your answer was better than mine anyway. Yours usually are. ;-) – David Jun 15 '12 at 17:07
  • You will also find that the CInt method is NOT in Microsoft.VisualBasic assembly. That is where all the old compatibility methods are at. – Robert Beaubien Jun 15 '12 at 17:19
  • 1
    @RobertBeaubien No - CInt is directly provided by the language. – Reed Copsey Jun 15 '12 at 17:22
  • Like I said with that big "NOT" in my statement. He was worried about using old stuff. – Robert Beaubien Jun 15 '12 at 17:34
  • @RobertBeaubien - No. The compatibility methods are in the Microsoft.VisualBasic.Compatibility assembly. Microsoft.VisualBasic contains namespaces such as CompilerServices, FileIO, and the My functionality and are not just for compatibility. – Chris Dunaway Jun 18 '12 at 14:18