Home » excel » Excel formula calculation in C#

Excel formula calculation in C#

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m having a bit of trouble with a calculation in Excel that needs to be written in C#.

The calculation in Excel is this:

=(26/1000*1,500+(0,0000039096*(26*26)+0,000082819*26+0,005066))*149468556,2
*(1+0,10%)

This gives the result of: 7310663,398

In C# I have the exact same calculation (except for more decimals in the 14949.. number:

(26.0 / 1000.0 * 1.500 + (0.0000039096 * (26.0 * 26.0) + 0.000082819 * 26.0 + 0.005066)) * 149468556.2 * (1 + 0.1);

Which gives this result: 7632589.7787303319

Since the last number in the formula is percent I’ve also tried this:

(26.0 / 1000.0 * 1.500 + (0.0000039096 * (26.0 * 26.0) + 0.000082819 * 26.0 + 0.005066)) * 149468556.2 * (1 + (0.1/100));

Which gives this result: 6945656.6986446008

Of course, I need to match the Excel result in C#, but I’m totally stuck on how to achieve this. Guess I should’ve listened closer in the math lessons 😉

Any help/input on this is greatly appreciated!

Thanks in advance.

All the best,

Bo

How to&Answers:

You have a typo. In Excel, you used (1+0,10%) and in C# you used (1 + 0.1).

Since 0.10% is really 0.10 / 100, you should use (1 + 0.001) instead.

So the correct C# would be:

(26.0 / 1000.0 * 1.500 + 
  (0.0000039096 * (26.0 * 26.0) + 0.000082819 * 26.0 + 0.005066)) * 
  149468556.2 * (1 + 0.001);

Answer:

My advice would be to keep all the decimals. It’s probably a precision mistake.

Your results are similar to what you should have which means it’s not a calculation mistake (like forgetting to divide by 100, etc. Which would show directly in your result).

Answer:

Well atleast this gives me the result

double ds = (26.0 / 1000.0 * 1.500 + (0.0000039096 * (26.0 * 26.0) + 0.000082819 * 26.0 + 0.005066)) * 149468556.2 * (1.0 + 0.1/100.0);
Console.WriteLine(ds.ToString());

result 7310663.39550679