Reputation:
I have a double value that I'd like to convert into a Int32. How can I check before converting if it can be converted?
Sometimes the value is undefined and the Converting into Int32 throws an OverflowException.
I already tried to test it that way:
double value = getSomeValue();
if (value == Double.NAN) {
value =0;
}
int v = Convert.ToInt32(value);
But this does not cover all cases.
Upvotes: 5
Views: 2295
Reputation: 128327
Maybe this?
Update: I believe the update below addresses the edge cases. I've tested this against every case I could think of verifying the output against a method that attempts Convert.ToInt32
directly and catches the exception.
static bool TryConvertToInt32(double value, out int result)
{
const double Min = int.MinValue - 0.5;
const double Max = int.MaxValue + 0.5;
// Notes:
// 1. double.IsNaN is needed for exclusion purposes because NaN compares
// false for <, >=, etc. for every value (including itself).
// 2. value < Min is correct because -2147483648.5 rounds to int.MinValue.
// 3. value >= Max is correct because 2147483648.5 rounds to int.MaxValue + 1.
if (double.IsNaN(value) || value < Min || value >= Max)
{
result = 0;
return false;
}
result = Convert.ToInt32(value);
return true;
}
Upvotes: 9
Reputation: 27864
You could compare to the range of an Int32.
if(value <= (double)Int32.MAX_VALUE && value >= (double)Int32.MIN_VALUE)
return (Int32)value;
return 0;
Of course, if you want to return Max/Min value when the double is too large, you could do this:
if(value <= (double)Int32.MAX_VALUE && value >= (double)Int32.MIN_VALUE)
return (Int32)value;
if(value > (double)Int32.MAX_VALUE)
return Int32.MAX_VALUE;
if(value < (double)Int32.MIN_VALUE)
return Int32.MIN_VALUE;
return 0;
Upvotes: 3
Reputation: 108800
You could try something like this:
(value>=Int32.MinValue)&&(value<=Int32.MaxValue)
This will probably falsely reject values which are outside the value range of int
but get rounded into it. So you might want to extent the interval a bit.
For example Int32.MaxValue+0.1
gets rejected.
How do you want to treat non integral doubles? This code accepts them and silently rounds away the fractional part. The suggestions based on int.TryParse(value.ToString(),...)
will throw consider such doubles invalid.
Upvotes: 0
Reputation: 27357
Try something like this:
double d = Double.NaN;
int i;
if(Int32.TryParse(d.ToString(), out i))
{
Console.WriteLine("Success");
Console.WriteLine(i);
} else {
Console.WriteLine("Fail");
}
Upvotes: 1
Reputation: 19928
Unless you absolutely need the performance, what about using exception handling?
Upvotes: 0
Reputation: 887443
Check whether Double.IsNaN and make sure it's between int.MinValue and int.MaxValue,
Upvotes: 3