问题描述
好吧,我意识到这是星期天的早,所以我希望我只是想念一些明显的东西:
Ok, I realize it's early on a Sunday so I hope I'm just missing something obvious:
我有这个功能:
private decimal CashConversion(decimal amount, decimal ratio)
{
if (ratio == 1) return amount;
decimal convertedAmount = amount / ratio;
return Math.Round(convertedAmount, 2);
}
当我这样称呼它时:
decimal tax = CashConversion(96.53, 15);
tax"变量等于 6.43.但是,96.53/15是6.435333333333333.将其四舍五入应返回6.44.我在这里想念什么吗?
The "tax" variable is equal to 6.43. However, 96.53/15 is 6.435333333333333. Rounding that to 2 places should return 6.44. Am I missing something here?
推荐答案
检查Math.Round 的文档:由于 2 是偶数,并且第二个数字之后的下一个数字是 5,因此根据 IEEE 标准 754 第 4 节,该值将被四舍五入.这称为银行家的四舍五入em>.
Check the documentation for Math.Round: As 2 is even, and the next digit after the second is 5, the value is rounded down, according to the IEEE Standard 754, section 4. It's called banker's rounding.
这不是错误,而是预期的行为.也许不是您您所期望的.
It's not an error, but an expected behaviour. Maybe not the one you were expecting though.
但是,如果您希望数学上正确"的行为,则可以调用十进制.Round(Decimal,Int32,MidpointRounding)重载,如:
If you want the "mathematically correct" behaviour though, you can call the Decimal.Round(Decimal, Int32, MidpointRounding) overload, as in:
Math.Round(convertedAmount, 2, MidpointRounding.AwayFromZero);
这篇关于C# Math.Round 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!