Why does System.MidpointRounding.AwayFromZero not round up in this instance?

后端 未结 5 1367
星月不相逢
星月不相逢 2020-12-03 06:55

In .NET, why does System.Math.Round(1.035, 2, MidpointRounding.AwayFromZero) yield 1.03 instead of 1.04? I feel like the answer to my question lies in the sect

5条回答
  •  一个人的身影
    2020-12-03 07:18

    The binary representation of 1.035d is 0x3FF08F5C28F5C28F, which in fact is 1.03499999999999992006394222699E0, so System.Math.Round(1.035, 2, MidpointRounding.AwayFromZero) yield 1.03 instead of 1.04, so it's correct.

    However, the binary representation of 4.005d is 0x4010051EB851EB85, which is 4.00499999999999989341858963598, so System.Math.Round(4.005, 2, MidpointRounding.AwayFromZero) should yield 4.00, but it yield 4.01 which is wrong (or a smart 'fix'). If you check it in MS SQL select ROUND(CAST(4.005 AS float), 2), it's 4.00 I don't understand why .NET apply this 'smart fix' which makes things worse.

    You can check binary representation of a double at: http://www.binaryconvert.com/convert_double.html

提交回复
热议问题