【问题标题】:VB.Net Why does Math.Round round 5 to the nearest even number, and what can I do about it? [duplicate]VB.Net 为什么 Math.Round 将 5 舍入到最接近的偶数,我该怎么办? [复制]
【发布时间】:2013-12-16 17:28:03
【问题描述】:

为什么 Math.Round(0.125, 2) 舍入为 0.12?

Dim foo As Decimal
foo = Math.Round(0.125, 2)

foo 现在是 0.12,但应该是 0.13

我听说这是因为 .Net 中的某些标准四舍五入到最接近的偶数,但这只是糟糕的数学。 12.5 将向下舍入为 12,但 13.5 将向上舍入为 14。有没有办法解决这个问题?

【问题讨论】:

  • 仅供参考,这被称为“银行家四舍五入”。
  • 这是银行家的四舍五入。使用带有 MidpointRounding 参数的 Round() 重载来更改它。

标签: .net vb.net


【解决方案1】:

来自documentation 方法上的Math.Round(decimal)

如果d的小数部分在两个整数的中间,其中一个为偶数,另一个为奇数,则返回偶数。

同样的逻辑也适用于Math.Round(decimal, int) 重载。注意:

Math.Round(0.125, 2) // 0.12
Math.Round(0.135, 2) // 0.14
Math.Round(0.145, 2) // 0.14

这不是“糟糕的数学”;这是一种常见的舍入策略,称为“舍入到偶数”。来自Wikipedia

这种舍入到最近方法的变体也称为无偏舍入收敛舍入统计学家的舍入荷兰语舍入高斯舍入奇偶舍入庄家舍入断舍入,以及广泛用于簿记。

这是 IEEE 754 计算函数和运算符中使用的默认舍入模式。

如果你想更好地控制它的舍入方式,你可以指定一个MidpointRounding 参数

Math.Round(0.125, 2, MidpointRounding.AwayFromZero) // 0.13

【讨论】:

  • 啊,MidpointRounding.AwayFromZero 成功了。我每天都学到新东西。谢谢!
猜你喜欢
  • 2014-04-21
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
相关资源
最近更新 更多