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

后端 未结 4 744
情深已故
情深已故 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:20

    From documentation;

    The integer nearest a. 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. Note that this method returns a Double instead of an integral type.

    Math.Round method has some overloads that takes MidpointRounding as a parameter which you can specify the rounding value if it is midway between two numbers.

    AwayFromZero 
    

    When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.

    ToEven
    

    When a number is halfway between two others, it is rounded toward the nearest even number.

提交回复
热议问题