Got hit by an OverflowException

时光总嘲笑我的痴心妄想 提交于 2021-02-04 13:14:25

问题


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

回答1:


Also check double.IsNaN(value).

Compares with NaN always yield false.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/5194854/got-hit-by-an-overflowexception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!