Best (safest) way to convert from double to int

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

    Option 3a not using exceptions, always returns a value:

        Int32 Convert(Double d)
        {
            if (d <= (double)Int32.MinValue)
                return Int32.MinValue;
            else if (d >= (double)Int32.MaxValue)
                return Int32.MaxValue;
            else 
                return (Int32)d;
        }
    

提交回复
热议问题