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

前端 未结 15 1993
灰色年华
灰色年华 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:39

    From MSDN, Math.Round(double a) returns:

    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.

    ... and so 2.5, being halfway between 2 and 3, is rounded down to the even number (2). this is called Banker's Rounding (or round-to-even), and is a commonly-used rounding standard.

    Same MSDN article:

    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. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.

    You can specify a different rounding behavior by calling the overloads of Math.Round that take a MidpointRounding mode.

提交回复
热议问题