相关疑难解决方法(0)

为什么.NET使用银行家的舍入作为默认值?

根据文档,该decimal.Round方法使用round-to-even算法,这对于大多数应用程序来说并不常见.所以我总是最终编写一个自定义函数来做更自然的圆半算法:

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;
}
Run Code Online (Sandbox Code Playgroud)

有谁知道这个框架设计决策背后的原因?

是否有任何内置的圆形半算法实现到框架中?或者可能是一些非托管Windows API?

对于初学者而言,这可能会产生误导,因为他们只是写了一个decimal.Round(2.5m, 0)期望3但结果是2.

.net rounding

264
推荐指数
4
解决办法
5万
查看次数

标签 统计

.net ×1

rounding ×1