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


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01