convert double to int

user496949 picture user496949 · Nov 15, 2010 · Viewed 328.3k times · Source

What is the best way to convert a double to an int? Should a cast be used?

Answer

Jon Skeet picture Jon Skeet · Nov 15, 2010

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.