Best (safest) way to convert from double to int

I prefer option 2.

One thing you need to do is check for exceptions though to confirm it worked, the same way you're checking 'parsed' in option 1:

try
{
    bar = Convert.ToInt32(foo); 
}
catch(OverflowException)
{
    // no can do!
{

If you were converting string etc instead of double, you might get a 'FormatException' instead.

Edit

I originally said option 2 wasn't particularly better than option 1, which @0xA3 pointed out was wrong. Option 1 is worse because it converts to a string before being parsed to an integer, which means it's less efficient. You also don't get an OverflowException if the double is outside the integer range (which you may or may not want) - although 'parsed' will be False in this case.


I think your best option would be to do:

checked
{
    try
    {
        int bar = (int)foo;
    }
    catch (OverflowException)
    {
     ...          
    }
}

From Explicit Numeric Conversions Table

When you convert from a double or float value to an integral type, the value is truncated. If the resulting integral value is outside the range of the destination value, the result depends on the overflow checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.

Note: Option 2 also throws an OverflowExceptionwhen required.


I realize this is not quite what the OP was asking for, but this info could be handy.

Here is a comparison (from http://www.dotnetspider.com/resources/1812-Difference-among-Int-Parse-Convert-ToInt.aspx)

        string s1 = "1234";
        string s2 = "1234.65";
        string s3 = null;
        string s4 = "12345678901234567890123456789012345678901234567890";

        int result;
        bool success;

        result = Int32.Parse(s1);      // 1234
        result = Int32.Parse(s2);      // FormatException
        result = Int32.Parse(s3);      // ArgumentNullException
        result = Int32.Parse(s4);      // OverflowException

        result = Convert.ToInt32(s1);      // 1234
        result = Convert.ToInt32(s2);      // FormatException
        result = Convert.ToInt32(s3);      // 0
        result = Convert.ToInt32(s4);      // OverflowException

        success = Int32.TryParse(s1, out result);      // 1234
        success = Int32.TryParse(s2, out result);      // 0
        success = Int32.TryParse(s3, out result);      // 0
        success = Int32.TryParse(s4, out result);      // 0