VB.Net 中的 Math.Round() 有什么问题? [英] What is wrong with Math.Round() in VB.Net?

查看:64
本文介绍了VB.Net 中的 Math.Round() 有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 VB.Net 中的 Math.Round 函数中遇到了一个奇怪的情况

I have encountered a weird case in Math.Round function in VB.Net

Math.Round((32.625), 2)

结果:32.62

Math.Round((32.635), 2)

结果:32.64

我需要 32.63,但在这些情况下,该函数以不同的逻辑运行.

I need 32.63 but the function is working in different logic in these cases.

我可以得到小数部分并在上面做我想做的事情.但这不是太奇怪了,一个是四舍五入到更高,一个是四舍五入到更低.

I can get the decimal part and make what I want doing something on it. But isn't this too weird, one is rounding to higher, one is rounding to lower.

那么我怎样才能从 32.625 得到 32.63 而不会弄乱小数部分呢?(作为数学的自然逻辑)

So how can I get 32.63 from 32.625 without messing with decimal part ? (as the natural logic of Maths)

推荐答案

Math.Round 默认使用 banker's rounding.您可以通过指定不同的 MidPointRounding 选项来更改它.来自 MSDN:

Math.Round uses banker's rounding by default. You can change that by specifying a different MidPointRounding option. From the MSDN:

从零开始舍入

中点值四舍五入到远离零的下一个数字.为了例如,3.75 轮到 3.8,3.85 轮到 3.9,-3.75 轮到 -3.8,和 -3.85 轮到 -3.9.这种四舍五入形式表示为MidpointRounding.AwayFromZero 枚举成员.舍入远离零是最广为人知的舍入形式.

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.

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

中点值四舍五入到最接近的偶数.例如,3.75 和 3.85 都舍入到 3.8,-3.75 和 -3.85 都舍入到-3.8.这种形式的舍入由 MidpointRounding.ToEven 枚举成员表示.

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.

四舍五入是财务中使用的标准四舍五入形式和统计操作.它符合 IEEE 标准 754,部分4.在多次舍入操作中使用时,减少了由于在一次舍入中一致舍入中点值而导致的舍入误差单一方向.在某些情况下,这种舍入误差可以是很重要.

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, 2, MidpointRounding.AwayFromZero)

正如其他人提到的,如果精度很重要,您应该使用 Decimal 变量而不是浮点类型.例如:

As others have mentioned, if precision is important, you should be using Decimal variables rather than floating point types. For instance:

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

这篇关于VB.Net 中的 Math.Round() 有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆