Bitten by division rounding?

瘦欲@ 提交于 2020-07-09 02:58:01

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!