Why does the following code:
Console.WriteLine(String.Format("{0:C0}", 2170/ 20));
yield "$109", while doing
Console.WriteLine(Math.Round(2170 / 20));
gives me 108?
How can I get 2170 / 20 give me 109?
Why does the following code:
Console.WriteLine(String.Format("{0:C0}", 2170/ 20));
yield "$109", while doing
Console.WriteLine(Math.Round(2170 / 20));
gives me 108?
How can I get 2170 / 20 give me 109?
When you divide to values of integral type, such as 2170 and 20, the runtime performs an integer division and discards (truncates) the decimal.
If you change one of the operands to a float, double, or decimal (eg, 2170.0 / 20, or 2170 / 20m), it will perform a floating-point division, as you would expect.
Therefore, you need to change it to
Console.WriteLine(Math.Round(2170.0 / 20));
Like this:
Math.Round(2170m / 20, MidpointRounding.AwayFromZero)