Best (safest) way to convert from double to int

前端 未结 8 918
感情败类
感情败类 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.

提交回复
热议问题