Math.Round((32.625),2)
结果:32.62
Math.Round((32.635),2)
结果:32.64
我需要32.63,但是在这些情况下,这个功能正在不同的逻辑上工作.
我可以得到小数部分,并使我想要做的事情.但这不是太奇怪了,一个是四舍五入,一个是四舍五入.
那么如何从32.625得到32.63,而不会搞乱小数部分? (作为数学的自然逻辑)
从零舍入
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)