convert double to int
What is the best way to convert a double
to an int
? Should a cast be used?
Solution 1:
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.
Solution 2:
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
Solution 3:
Yeah, why not?
double someDouble = 12323.2;
int someInt = (int)someDouble;
Using the Convert
class works well too.
int someOtherInt = Convert.ToInt32(someDouble);