The cleanest way to convert `Double` or` Single` to `Integer`, without rounding

Converting a floating point number to an integer using CInt or CTypewill round up the value of that number. The function Intand Math.Floorcan be used to convert a floating point number to an integer, rounded to negative infinity, but both functions return floating point values ​​that cannot be implicitly used as values Integerwithout casts.

Is there a condensed and idiomatic alternative IntVar = CInt(Int(FloatingPointVar));? Pascal included functions Roundand Truncthat returned Integer; Is there any equivalent in VB.NET or in the .NET framework?

A similar CInt question does not round a double value sequentially - how can I remove the fractional part? was asked in 2011, but he just asked if there was a way to convert a floating point number to an integer; the answers suggested a two-step process, but it did not go deep into what exists or does not exist within the framework. It would be hard for me to believe that the Framework would not have anything similar to the Pascal function Trunc, given that such a thing will often be necessary when performing graphical operations using floating point operands [such operations should be displayed as discrete pixels and should be rounded so that round (x) -1 = round (x-1) for all x which correspond to the range +/- (2 ^ 31-1); even if such operations are rounded, they should use Floor (x + 0.5) rather than rounding to the nearest-even to ensure the specified property]

By the way, in C # type-type from Doubleto Intusing notation (type)expruses the semantics of round-to-zero; the fact that this is different from the behavior of VB.NET suggests that one or both languages ​​use their own conversion procedures, rather than the explicit conversion operator included in the Framework. It would seem that the Framework should define a conversion operator? Does such an operator exist in the framework? What does it do? Is there a way to call it from C # and / or VB.NET?

+5
source share
3 answers

After some searching, it seems that VB has no clean way to accomplish this unless you write an extension method.

# (int) cast conv.i4 IL. VB , , -, .

2005 - , , , , .

+4

Math.Truncate.

.

:

Dim a As double = 1.6666666
Dim b As Integer = Math.Truncate(a) ' b = 1
+1

You may need to extract the int part of the floating point number:

float num = 12.234;
string toint = "" + num;
string auxil = toint.Split('.');
int newnum = Int.Parse(auxil[0]);
-4
source

All Articles