根据文档,
decimal.Round
方法使用的是舍入到偶数算法,这在大多数应用程序中并不常见。因此,我总是编写自定义函数来执行更自然的四舍五入算法: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的初学者,这可能会产生误导。