根据文档,decimal.Round http://msdn.microsoft.com/en-us/library/zy06z30k.aspx方法使用舍入到偶数算法,这对于大多数应用程序来说并不常见。因此,我总是最终编写一个自定义函数来执行更自然的四舍五入算法:
public static decimal RoundHalfUp(this decimal d, int decimals)
{
if (decimals < 0)
{
throw new ArgumentException("The decimals must be non-negative",
"decimals");
}
decimal multiplier = (decimal)Math.Pow(10, decimals);
decimal number = d * multiplier;
if (decimal.Truncate(number) < number)
{
number += 0.5m;
}
return decimal.Round(number) / multiplier;
}
有人知道这个框架设计决策背后的原因吗?
框架中是否有内置的上舍入算法实现?或者也许是一些非托管的 Windows API?
对于初学者来说,简单地写可能会产生误导decimal.Round(2.5m, 0)
期望结果为 3,但得到的却是 2。
其他人回答了银行家算法(又名四舍五入到偶数 http://en.wikipedia.org/wiki/Rounding#Round_half_to_even)是一个不错的选择,非常正确。它不会像其他人那样受到负面或正面偏见的影响从零舍入一半 http://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero最合理分布的方法。
但问题是为什么 .NET 使用 Banker 的实际舍入作为默认值 - 答案是 Microsoft 遵循了IEEE 754 https://en.wikipedia.org/wiki/IEEE_754#Roundings_to_nearest标准。这一点在Math.Round 的 MSDN http://msdn.microsoft.com/en-us/library/system.math.round.aspx在备注下。
另请注意,.NET 通过提供MidpointRounding
枚举。他们当然可以提供更多选择 http://en.wikipedia.org/wiki/Rounding#Tie-breaking来解决联系,但他们选择只满足 IEEE 标准。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)