Best (safest) way to convert from double to int

前端 未结 8 889
感情败类
感情败类 2021-01-07 21:00

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 wou

8条回答
  •  北海茫月
    2021-01-07 21:42

    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.

提交回复
热议问题