Overflow Exception when dividing two decimals in .NET

Deadly 提交于 2019-12-05 15:34:49

Try converting to double before calculating, and back to decimal afterwards if you need:

decimal dOne = -966.96M;
decimal dTwo = 2300M;

double one = (double)dOne;
double two = (double)dTwo;

double result = one / two;

decimal dResult = (decimal)result; // Additional rounding may be necessary

That should run fine. The division isn't guaranteed to return the exactly accurate version - for example, 1 / 3m works fine.

The result clearly isn't outside the range of decimal, so it looks to me like something weird is going on on your server.

One thing to check: is it Decimal.Round that's throwing the exception, or the division itself? Put them into separate statements to find out.

If it happens on your sever (where you can't debug). Are you really sure that the problem is within these lines?

Maybe you can put a try-catch statement around only the single Decimal.Round statement and giving back some weird value instead. This code could you run on your server again to see if this catch statement really gets called or if the Exception maybe happens somewhere else.

I looked at Decimal.Round via Reflector and from what I see it does not ever throw OverflowException so I am betting the exception is coming from the division. Can you edit your answer to include the stack trace?

Also, are you absolutely certain that the numerator and denominator are exactly as you have written? Try tracing the them to the console or a log file when the exception occurs.

You could do something like this:

decimal dOne = -966.96M; 
decimal dTwo = 2300M;  
try
{
  decimal dResult = Decimal.Round((dOne / dTwo), 28, MidpointRounding.AwayFromZero); 
}
catch (OverflowException)
{
  Console.WriteLine(dOne);
  Console.WriteLine(dTwo);
}

Edit: I think I found the code to FCallDivide in the SSCLI. However, it is likely to be different in the release version of the .NET Framework, but I can see from the way it was done in the SSCLI anyway that an overflow exception will be generated in a lot of different ways. The code is quite complicated. If you can construct a short but complete program demonstrating the problem I would submit it as a bug to Microsoft. It is possible that there is a certain bit pattern in those inputs that is confusing the algorithm.

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