根据文档,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,这可能会误导他们.