Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do .Net and Excel not agree on this math? [duplicate]

Tags:

c#

math

excel

I'm having some really strange behaviour from some C# and Excel ...

Having done the math myself I believe that excel may be giving the correct answer but my math aint great so it may be that the .Net compiler knows something I don't.

So here we go ...

Given this data in the form of an excel sheet:

total     sale val  days    irr
2431.65   2424.56   21      5.01

The formula for irr (cell D2) is as follows:

=ROUND(100 * ((A2 - B2) / B2) * (360 / C2), 2)

When I run this C# I get the result 4.97 ...

var totalIncludingTax = 2431.65M;
var saleValue = 2424.56M;
var daysRemaining = 21;

var result = Math.Round(100.0m * ((totalIncludingTax - saleValue) / saleValue) * (360 / daysRemaining), 2);

Can anyone explain how I can force C# / .Net and Excel to agree / how I might rewrite this formula so that the two agree?

like image 942
War Avatar asked Feb 07 '23 21:02

War


1 Answers

360 / daysRemaining

This becomes an integer division in C#: 360/21 = 17 and not 17.14285714 as it will be in Excel.

Change it to 360.0 /daysRemaining to make it a floating point operation (or 360m as it has also been pointed out).

like image 188
Dan Byström Avatar answered Feb 10 '23 12:02

Dan Byström