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

查看:159
本文介绍了为什么.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天全站免登陆