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

Why does .NET use banker#39;s rounding as default?(为什么.NET 默认使用银行家的四舍五入?)
本文介绍了为什么.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 默认使用银行家的四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)