VB.Net 为什么 Math.Round 将 5 舍入到最接近的偶数,我该怎么办?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20616930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:09:59  来源:igfitidea点击:

VB.Net Why does Math.Round round 5 to the nearest even number, and what can I do about it?

.netvb.net

提问by BClaydon

Why is Math.Round(0.125, 2) rounding to 0.12?

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

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

foo is now 0.12 but it should b 0.13

foo 现在是 0.12 但它应该是 0.13

I heard it's because some standard in .Net rounds to the nearest even number, but that's just bad math. 12.5 will round down to 12, but 13.5 will round up to 14. Is there a way to fix this?

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

回答by p.s.w.g

From the documentationon the Math.Round(decimal)method:

从该方法的文档中Math.Round(decimal)

If the fractional component of dis halfway between two integers, one of which is even and the other odd, the even number is returned.

如果d的小数部分介于两个整数之间,其中一个是偶数,另一个是奇数,则返回偶数。

The same logic applies to the Math.Round(decimal, int)overload. Notice:

相同的逻辑适用于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

It's not 'bad math'; it's a common rounding strategy known as 'round-to-even'. From Wikipedia:

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

This variant of the round-to-nearest method is also called unbiased rounding, convergent rounding, statistician's rounding, Dutch rounding, Gaussian rounding, odd-even rounding, bankers' roundingor broken rounding, and is widely used in bookkeeping.

This is the default rounding mode used in IEEE 754 computing functions and operators.

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

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

If you want finer control over how it rounds, you can specify a MidpointRoundingparameter

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

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