I am looking for the C# equivalent of the following Excel formula:
(INT(((4800/1000)/0.415)*2.393)/0.05)
I get the value 540
with the above formula in Excel, but now I am trying to do the same in C# with the following code:
Math.Round((((4800 /1000) / 0.415) * 2.393) / 0.05, 0)
I get the value 553
.
How can I get the same value with my C# coding?
That's what you need:
(int)(((4800.0 /1000) / 0.415) * 2.393) / 0.05
Or alternatively:
(int)((((double)4800 / 1000) / 0.415) * 2.393) / 0.05
The problem is that the 4800 and 1000 literals are interpreted as integers, and in C# dividing two integers yields you another rounded integer. So 4800/1000 = 4, but you want 4.8.
By adding the .0
part you are implicitly converting the literal to a double, or you can also do an explicit cast. Dividing a double by an integer already gives you a double.
You can try this:
using System;
public class Test
{
public static void Main()
{
Console.WriteLine((int)((((double)4800 / 1000) / 0.415) * 2.393) / 0.05);
}
}
IDEONE DEMO
Integer divided by Integer(4800/1000) results in a integer(4) as against the excel result(4.8) which you are getting as double. So you need to cast it to double.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With