CInt(Double)
is compiled to implicit cast that calls the default Math.Round(Double)
and converts the result to Integer
, so the main reasons to use Math.Round(Double, MidpointRounding.AwayFromZero)
instead of CInt(Double)
would be
- to use the
MidpointRounding.AwayFromZero
rounding instead of the default MidpointRounding.ToEven
rounding
- to avoid
System.OverflowException
when the result can't fit in Integer
(Anything smaller than Integer.MinValue
or larger than Integer.MaxValue
such as Dim d = 2 ^ 31
)
- if
CInt(1.5)
in VB.Net is converted carelessly to (int)1.5
in C#, small rounding errors might occur. In VB.Net CInt(1.5)
is 2, but in c# (int)1.5
is 1.
The CIL bytecode generated (in VS 2010 .NET 3.5) from
Dim d As Double = 2.5
Dim i1 As Integer = CInt(d) ' 2
Dim i2 As Integer = CType(d, Integer) ' 2
Dim i3 As Integer = d ' 2
Dim d2 = Int(d) ' 2.0
in ildasm.exe is:
IL_000f: ldc.r8 2.5
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: call float64 [mscorlib]System.Math::Round(float64)
IL_001f: conv.ovf.i4
IL_0020: stloc.2
IL_0021: ldloc.0
IL_0022: call float64 [mscorlib]System.Math::Round(float64)
IL_0027: conv.ovf.i4
IL_0028: stloc.3
IL_0029: ldloc.0
IL_002a: call float64 [mscorlib]System.Math::Round(float64)
IL_002f: conv.ovf.i4
IL_0030: stloc.s i3
IL_0032: ldloc.0
IL_0033: call float64 [Microsoft.VisualBasic]Microsoft.VisualBasic.Conversion::Int(float64)
IL_0038: stloc.1
which shows that the 3 conversions compile to the same call to the default Math.Round(Double)
and conv.ovf.i4
Integer conversion.