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 would be my secondary concern). I've left a few options I can come up with below. Can anyone weigh in on which is best practice? Any better ways to accomplish this that I haven't listed?
double foo = 1;
int bar;
// Option 1
bool parsed = Int32.TryParse(foo.ToString(), out bar);
if (parsed)
{
//...
}
// Option 2
bar = Convert.ToInt32(foo);
// Option 3
if (foo < Int32.MaxValue && foo > Int32.MinValue) { bar = (Int32)foo; }
I think your best option would be to do:
checked
{
try
{
int bar = (int)foo;
}
catch (OverflowException)
{
...
}
}
From Explicit Numeric Conversions Table
When you convert from a double or float value to an integral type, the value is truncated. If the resulting integral value is outside the range of the destination value, the result depends on the overflow checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.
Note: Option 2 also throws an OverflowException
when required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With