convert double to int
if you use cast, that is, (int)SomeDouble
you will truncate the fractional part. That is, if SomeDouble
were 4.9999 the result would be 4, not 5. Converting to int doesn't round the number. If you want rounding use Math.Round
The best way is to simply use Convert.ToInt32
. It is fast and also rounds correctly.
Why make it more complicated?
Yeah, why not?
double someDouble = 12323.2;
int someInt = (int)someDouble;
Using the Convert
class works well too.
int someOtherInt = Convert.ToInt32(someDouble);
You can use a cast if you want the default truncate-towards-zero behaviour. Alternatively, you might want to use Math.Ceiling
, Math.Round
, Math.Floor
etc - although you'll still need a cast afterwards.
Don't forget that the range of int
is much smaller than the range of double
. A cast from double
to int
won't throw an exception if the value is outside the range of int
in an unchecked context, whereas a call to Convert.ToInt32(double)
will. The result of the cast (in an unchecked context) is explicitly undefined if the value is outside the range.