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

VB.Net中的Math.Round()有什么问题?

发布时间:2020-12-17 00:09:17 所属栏目:大数据 来源:网络整理
导读:我在VB.Net中的Math.Round函数中有一个非常奇怪的情况 Math.Round((32.625),2) 结果:32.62 Math.Round((32.635),2) 结果:32.64 我需要32.63,但是在这些情况下,这个功能正在不同的逻辑上工作. 我可以得到小数部分,并使我想要做的事情.但这不是太奇怪了,一个
我在VB.Net中的Math.Round函数中有一个非常奇怪的情况
Math.Round((32.625),2)

结果:32.62

Math.Round((32.635),2)

结果:32.64

我需要32.63,但是在这些情况下,这个功能正在不同的逻辑上工作.

我可以得到小数部分,并使我想要做的事情.但这不是太奇怪了,一个是四舍五入,一个是四舍五入.

那么如何从32.625得到32.63,而不会搞乱小数部分? (作为数学的自然逻辑)

Math.Round默认使用银行家的四舍五入.您可以通过指定不同的MidPointRounding选项进行更改.从 MSDN:

从零舍入

Midpoint values are rounded to the next number away from zero. For
example,3.75 rounds to 3.8,3.85 rounds to 3.9,-3.75 rounds to -3.8,
and -3.85 rounds to -3.9. This form of rounding is represented by the
MidpointRounding.AwayFromZero enumeration member. Rounding away from
zero is the most widely known form of rounding.

舍入到最近,或银行家的四舍五入

Midpoint values are rounded to the nearest even number. For example,
both 3.75 and 3.85 round to 3.8,and both -3.75 and -3.85 round to
-3.8. This form of rounding is represented by the MidpointRounding.ToEven enumeration member.

Rounding to nearest is the standard form of rounding used in financial
and statistical operations. It conforms to IEEE Standard 754,section
4. When used in multiple rounding operations,it reduces the rounding error that is caused by consistently rounding midpoint values in a
single direction. In some cases,this rounding error can be
significant.

所以,你想要的是:

Math.Round(32.625,2,MidpointRounding.AwayFromZero)
Math.Round(32.635,MidpointRounding.AwayFromZero)

正如其他人所说,如果精度很重要,你应该使用十进制变量而不是浮点类型.例如:

Math.Round(32.625D,MidpointRounding.AwayFromZero)
Math.Round(32.635D,MidpointRounding.AwayFromZero)

(编辑:李大同)

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

    推荐文章
      热点阅读