为什么 .NET 使用银行家的舍入作为默认值? [英] Why does .NET use banker's rounding as default?

查看:22
本文介绍了为什么 .NET 使用银行家的舍入作为默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档,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 使用银行家的舍入作为默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆