Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflow Exception when dividing two decimals in .NET

I'm having an issue trying to divide two decimals and then display the result. Annoyingly this is only happening on our server, and it appears to work perfectly fine if I run the code locally. This is the code that I am trying to run


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

decimal dResult = Decimal.Round((dOne / dTwo), 28, 
                               MidpointRounding.AwayFromZero);

The resulting number (as generated from windows calculator) is

-0.43346086956521739130434782608696

This always results in an overflow exception:

System.OverflowException: Value was either too large or too small for a Decimal.
   at System.Decimal.FCallDivide(Decimal& result, Decimal d1, Decimal d2)
   at System.Decimal.op_Division(Decimal d1, Decimal d2)

This does kind of make sense as the resulting number is over 32 decimal places long, and a decimal can only hold up to 28 places..but I am not sure how to perform this division as it appears to be storing the result in the decimal type in memory, before rounding it off and storing it. I've also tried converting it directly to a string rather than storing it in a decimal, but that has the same problem.

Any ideas? Have I done something obviously silly (most probably) and is there a better way to perform this calculation?

like image 381
Spud1 Avatar asked Dec 28 '22 11:12

Spud1


2 Answers

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
like image 86
Tomas Aschan Avatar answered Jan 18 '23 02:01

Tomas Aschan


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.

like image 20
Jon Skeet Avatar answered Jan 18 '23 03:01

Jon Skeet