加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

VB.Net为什么Math.Round在第5轮到最近的偶数,我该怎么办呢?

发布时间:2020-12-17 00:31:09 所属栏目:大数据 来源:网络整理
导读:参见英文答案 Why does .NET use banker’s rounding as default?5个 为什么Math.Round(0.125,2)舍入到0.12? Dim foo As Decimalfoo = Math.Round(0.125,2) foo现在是0.12但它应该是0.13 我听说这是因为.Net中的某些标准是最接近的偶数,但这只是糟糕的数学.
参见英文答案 > Why does .NET use banker’s rounding as default?5个
为什么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.有没有办法解决这个问题?

从Math000上的 documentation(十进制)方法:

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

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

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’ rounding or broken rounding,and is widely used in bookkeeping.

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读