为什么Math.Round(0.125,2)舍入到0.12?
Dim foo As Decimal foo = Math.Round(0.125,2)
foo现在是0.12但它应该是0.13@H_301_5@
我听说这是因为.Net中的某些标准是最接近的偶数,但这只是糟糕的数学. 12.5将向下舍入到12,但13.5将向上舍入到14.有没有办法解决这个问题?@H_301_5@
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.@H_301_5@
相同的逻辑适用于Math.Round(decimal,int)重载.注意:@H_301_5@
Math.Round(0.125,2) // 0.12 Math.Round(0.135,2) // 0.14 Math.Round(0.145,2) // 0.14
这不是’糟糕的数学’;这是一种常见的舍入策略,称为“从圆到偶”.从Wikipedia开始:@H_301_5@
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.@H_301_5@
This is the default rounding mode used in IEEE 754 computing functions and operators.@H_301_5@
如果想要更好地控制它的舍入方式,可以指定MidpointRounding参数@H_301_5@
Math.Round(0.125,2,MidpointRounding.AwayFromZero) // 0.13