Why does Math.Round(2.5) return 2 instead of 3?

前端 未结 15 2000
灰色年华
灰色年华 2020-11-22 03:54

In C#, the result of Math.Round(2.5) is 2.

It is supposed to be 3, isn\'t it? Why is it 2 instead in C#?

15条回答
  •  不知归路
    2020-11-22 04:28

    You should check MSDN for Math.Round:

    The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding.

    You can specify the behavior of Math.Round using an overload:

    Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // gives 3
    
    Math.Round(2.5, 0, MidpointRounding.ToEven); // gives 2
    

提交回复
热议问题