问题
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?
回答1:
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));
EDIT
Like this:
Math.Round(2170m / 20, MidpointRounding.AwayFromZero)
回答2:
Try Math.Round(2170.0 / 20.0)
来源:https://stackoverflow.com/questions/3498421/bitten-by-division-rounding