anon
anon

Reputation:

Got hit by an OverflowException

In the Method below on the last line I'm always getting an exception:

System.OverflowException: Value was either too large or too small for an Int32.

I can't really explain why because I'm checking explicitly for that:

private Int32 ConvertValue(double value)
{
   if (value > Int32.MaxValue)
   {
      Console.WriteLine("Couldn't convert value " + value + " to Int32");
      return Int32.MaxValue;
   }
   else if (value < Int32.MinValue)
   {
      Console.WriteLine("Couldn't convert value " + value + " to Int32");
      return Int32.MinValue;
   }
   else
   {
      return Convert.ToInt32(value);
   }
}

Upvotes: 12

Views: 886

Answers (3)

Henrik
Henrik

Reputation: 23324

Also check double.IsNaN(value).

Compares with NaN always yield false.

Upvotes: 14

Jon
Jon

Reputation: 437854

Here's the source from Microsoft's Convert.cs:

public static int ToInt32(double value) {
    if (value >= 0) {
        if (value < 2147483647.5) {
            int result = (int)value; 
            double dif = value - result;
            if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++; 
            return result; 
        }
    } 
    else {
        if (value >= -2147483648.5) {
            int result = (int)value;
            double dif = value - result; 
            if (dif < -0.5 || dif == -0.5 && (result & 1) != 0) result--;
            return result; 
        } 
    }
    throw new OverflowException(Environment.GetResourceString("Overflow_Int32")); 
}

I don't know what value you are feeding it, but the answer should be obvious now.

Upvotes: 3

James Bedford
James Bedford

Reputation: 28982

You get the exception every time you run this function with any double value?

It worked fine for me.

Edit: I created a program with the following code:

using System;
using System.Collections.Generic;
using System.Text;

namespace test1
{
    class Program
    {
        static void Main(string[] args)
        {
            Int32 myInt = ConvertValue(86389327923.678);
            Console.WriteLine(myInt);
                    myInt = ConvertValue(-86389327923.678);
            Console.WriteLine(myInt);
                    myInt = ConvertValue(8.678);
            Console.WriteLine(myInt);
            Console.ReadKey();
        }

        static private Int32 ConvertValue(double value)
        {
            if (value > Int32.MaxValue)
            {
                Console.WriteLine("Couldn't convert value " + value + " to Int32");
                return Int32.MaxValue;
            }
            else if (value < Int32.MinValue)
            {
                Console.WriteLine("Couldn't convert value " + value + " to Int32");
                return Int32.MinValue;
            }
            else
            {
                return Convert.ToInt32(value);
            }
        }
    }
}

Upvotes: 0

Related Questions