What is the best way to convert a double
to an int
? Should a cast be used?
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.