Reputation:
Links refer to Google Sheets and dotnetfiddle.net, respectively. I'm using MS Excel in my work, but in the example I'm using Google Sheets that returns the same value as MS Excel.
I'm transporting MS Excel calculations to SSIS using a script component with C# 2015.
The following Google Sheets formula returns 5.597718856:
=(0.31 * 102 / (9.38 + 58 / 12)) * (1 + (120 + 102 * 0.31) / 100)
When I try the same formula in C# the result is 5.94635605381166, a difference of 0.3486371983 which is a lot in my case.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine((0.31 * 102 / (9.38 + 58 / 12)) * (1 + (120 + 102 * 0.31) / 100)); // 5.94635605381166
}
}
Could someone explain to me what I am missing?
Upvotes: 0
Views: 131
Reputation: 219047
Excel is likely handling the numeric types differently, either inferring that the integers should be doubles or always handling numbers as doubles or something of that nature.
The C# code on the other hand has a lot of integer literals. So things like 58 / 12
end up being simply 4
with no remainder, because integer math produces an integer result.
You can explicitly define the values as doubles by appending a D
to them:
Console.WriteLine((0.31 * 102D / (9.38 + 58D / 12D)) * (1D + (120D + 102D * 0.31) / 100D));
Which produces the result you're looking for.
Upvotes: 1