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
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.
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);