Best (safest) way to convert from double to int

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

    Options (1) and (2) do essentially the same thing. Option (1) gives you an if (parsed) block whereas option (2) throws an error for any double that's not representable as an int.

    Option (3) is essentially the same as option (2) except it has an extra MinValue/MaxValue check which the others don't.

    In summary: these three pieces of code do different things. Option (3) looks to be the most robust, in that it has an extra range check.

    Edit: On second thoughts, use @Ani checked trick - you get the range check for free.

    0 讨论(0)
  • 2021-01-07 21:59

    I would use option two. Short, clean and it works.

    You could also look into the BigInteger class in .Net4, and you wouldn't have to check for overflow.

    double foo = 1;            
    BigInteger bigint = new BigInteger(foo);
    
    0 讨论(0)
提交回复
热议问题