How to check if Double can be converted to Int32?

I have a double value that I would like to convert to Int32. How can I check before conversion if it can be converted?

Sometimes the value is undefined, and conversion to Int32 raises an OverflowException.

I already tried to check it like this:

double value = getSomeValue();
if (value == Double.NAN) {
value =0;
}
int v = Convert.ToInt32(value);

But this does not apply to all cases.

+5
source share
6 answers

Maybe this?

Update . I believe the update below is for extreme cases. I tested this against every case that I could think of checking the output against a method that tries directly Convert.ToInt32and gets an 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;
}
+8

, Double.IsNaN , int.MinValue int.MaxValue,

+3

Int32.

if(value <= (double)Int32.MAX_VALUE && value >= (double)Int32.MIN_VALUE)
    return (Int32)value;
return 0;

, Max/Min, double , :

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;
+2

- :

double d = Double.NaN;
int i;
if(Int32.TryParse(d.ToString(), out i))
{
    Console.WriteLine("Success");
    Console.WriteLine(i);
} else {
    Console.WriteLine("Fail");
}   
+1

- :

(value>=Int32.MinValue)&&(value<=Int32.MaxValue)

, , , int, . , .

, Int32.MaxValue+0.1 .

? . , int.TryParse(value.ToString(),...), , , .

0

, ?

0
source

All Articles