Best (safest) way to convert from double to int

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

    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.

提交回复
热议问题