开发者

How to check if a Double can be converted into a Int32?

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.


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;
}


Check whether Double.IsNaN and make sure it's between int.MinValue and int.MaxValue,


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;


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");
}   


Unless you absolutely need the performance, what about using exception handling?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜