Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best (safest) way to convert from double to int

I'm curious as to the best way to convert a double to an int. Runtime safety is my primary concern here (it doesn't necessarily have to be the fastest method, but that would be my secondary concern). I've left a few options I can come up with below. Can anyone weigh in on which is best practice? Any better ways to accomplish this that I haven't listed?

        double foo = 1;
        int bar;

        // Option 1
        bool parsed = Int32.TryParse(foo.ToString(), out bar);
        if (parsed)
        {
            //...
        }

        // Option 2
        bar = Convert.ToInt32(foo);

        // Option 3
        if (foo < Int32.MaxValue && foo > Int32.MinValue) { bar = (Int32)foo; }
like image 865
Joel B Avatar asked Aug 23 '10 15:08

Joel B


1 Answers

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.

like image 174
Ani Avatar answered Sep 19 '22 12:09

Ani