开发者

Bitten by division rounding?

Why does the following code:

Console.WriteLine(String.Format("{0:C0}", 2170/ 20));

yield "$109", while doing

开发者_JS百科
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));

EDIT

Like this:

Math.Round(2170m / 20, MidpointRounding.AwayFromZero)


Try Math.Round(2170.0 / 20.0)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜