What is wrong with Math.Round() in VB.Net?

后端 未结 5 843
我寻月下人不归
我寻月下人不归 2020-12-06 10:08

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

Math.Round((32.625), 2)

Result : 32.62



        
5条回答
  •  离开以前
    2020-12-06 10:27

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

    Rounding away from zero

    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.

    Rounding to nearest, or banker's 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.

    So, what you want is:

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

    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)
    

提交回复
热议问题