问题描述
根据文档,decimal.Round
方法使用对大多数应用程序不常见的取整算法.所以我总是最终编写一个自定义函数来执行更自然的取整算法:
According to the documentation, the decimal.Round
method uses a round-to-even algorithm which is not common for most applications. So I always end up writing a custom function to do the more natural round-half-up algorithm:
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;
}
有人知道这个框架设计决策背后的原因吗?
Does anybody know the reason behind this framework design decision?
框架中是否有任何内置的半舍入算法实现?或者可能是一些非托管的 Windows API?
Is there any built-in implementation of the round-half-up algorithm into the framework? Or maybe some unmanaged Windows API?
对于简单地编写 decimal.Round(2.5m, 0)
期望结果为 3 却得到 2 的初学者来说,这可能会产生误导.
It could be misleading for beginners that simply write decimal.Round(2.5m, 0)
expecting 3 as a result but getting 2 instead.
推荐答案
可能是因为它的算法更好.在执行多次舍入的过程中,您将平均得出所有 0.5 的最终舍入均等.例如,如果您要添加一堆四舍五入的数字,这可以更好地估计实际结果.我想说的是,尽管这不是某些人所期望的,但这可能是更正确的做法.
Probably because it's a better algorithm. Over the course of many roundings performed, you will average out that all .5's end up rounding equally up and down. This gives better estimations of actual results if you are for instance, adding a bunch of rounded numbers. I would say that even though it isn't what some may expect, it's probably the more correct thing to do.
这篇关于为什么.NET 默认使用银行家的四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!