Best (safest) way to convert from double to int

前端 未结 8 1044
感情败类
感情败类 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:57

    If you really really need to find out if something went wrong, use a normal cast and check the result.

    int ToInt(double foo)
    {
        int result = (int)foo;
        if (foo != result)
            throw new ArgumentException()
    
        return result;
    }
    

    This will make sure no invalid conversion is done. If it is OK to round to nearest integer, use Math.Round and check if result is within 0.5. This will make sure no NaN or infinity will get by your method.

提交回复
热议问题