Math.Round returning a rounded up for odd values but rounds down for even

后端 未结 4 750
情深已故
情深已故 2021-01-13 12:34

I am trying to found a float using math round I found the following

0.5 --> 0
1.5 --> 2
2.5 --> 2
3.5 --> 4

and so on. I believ

4条回答
  •  天涯浪人
    2021-01-13 13:15

    You may try like this

     Math.Round(value, MidpointRounding.AwayFromZero);
    

    From MSDN

    If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned.

    Also to mention one important point which I think is good to mention is that Microsoft has followed the IEEE 754 standard. This is also mentioned in MSDN for Math.Round under Remarks which says:

    Round to nearest, ties to even – rounds to the nearest value; if the number falls midway it is rounded to the nearest value with an even (zero) least significant bit, which occurs 50% of the time; this is the default for binary floating-point and the recommended default for decimal.

    Round to nearest, ties away from zero – rounds to the nearest value; if the number falls midway it is rounded to the nearest value above (for positive numbers) or below (for negative numbers); this is intended as an option for decimal floating point.

提交回复
热议问题