Getting different result in Math.Round

强颜欢笑 提交于 2019-12-25 04:08:14

问题


ticketPriceInPence = 7360
percentageToRefund = 100

(int)(Math.Round((ticketPriceInPence * 0.01) * (percentageToRefund * 0.01), 2, MidpointRounding.AwayFromZero) * 100)

This results in : 73.59

(int)(Math.Round((ticketPriceInPence * 0.01) * (percentageToRefund * 0.01) * 100, 2, MidpointRounding.AwayFromZero))

This results in : 73.60

Any idea why it results in different 2 different results


回答1:


It's the old case of floating point numbers not being able to represent decimals exactly.

You seem to be dealing with money here and then you really should consider using decimal.

decimal ticketPriceInPence = 7360;
decimal percentageToRefund = 100;
var result1 = (int)(Math.Round((ticketPriceInPence * 0.01m) * (percentageToRefund * 0.01m), 2, MidpointRounding.AwayFromZero) * 100);
var result2 = (int)(Math.Round((ticketPriceInPence * 0.01m) * (percentageToRefund * 0.01m) * 100, 2, MidpointRounding.AwayFromZero));



回答2:


The simple answer is that it's due to rounding error in equations using floating point numbers. This is because, in general, there is no exact binary representation of a floating point number so all you've got is approximations.

I notice you've got:

(percentageToRefund * 0.01)

in the first equation, and:

(percentageToRefund * 0.01) * 100

in the second.

This latter expression will result in rounding error as you are first dividing by 100 then multiplying by 100 again. The input won't equal the output, the difference depending on machine architecture, OS, language and compiler.

If you're dealing with money you should use decimal type (assuming C#)




回答3:


Because a float is not an exact number. I recommend reading http://en.wikipedia.org/wiki/Floating_point. You will see why the result is different.




回答4:


Long story short. It's because of precision erros when representing float values as binary data. That basically means you can't represent every possible float with 32/64 Bits, so 2.1 in reality is 2.1000000000000001 etc. That's one reason why you should never do something like 2.145 == "other value that should be 2.145".

I suggest reading the article at wikipedia for more detailed information: Wiki Link




回答5:


This is due to the finite precision of floating point numbers.



来源:https://stackoverflow.com/questions/1606664/getting-different-result-in-math-round

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