问题
The following applies:
var rounded = Decimal.Round(7.635m, 2);
//rounded: 7.63
This, to me, is wrong and unexpected behavior. I would assume the value of rounded to be 7.64.
To achieve this, I can do:
var rounded = Decimal.Round(7.635m, 2, MidpointRounding.AwayFromZero);
//rounded: 7.64
How can this not be the default behavior of Decimal.Round
? Any good reason for this?
回答1:
How can this not be the default behavior of Decimal.Round? Any good reason for this?
If you look at the documentation of Decimal.Round Method (Decimal)
The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called round half to even or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction. It is equivalent to calling the Round(Decimal, MidpointRounding) method with a mode argument of MidpointRounding.ToEven.
回答2:
From Math.Round(Decimal, Int32) Method
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.
This method is equivalent to calling the Round method with a mode argument of MidpointRounding.ToEven. If there is a single non-zero digit in d to the right of the decimals decimal position and its value is 5, the digit in the decimals position is rounded up if it is odd, or left unchanged if it is even. If d has fewer fractional digits than decimals, d is returned unchanged.
回答3:
The reason is they implemented a method following IEEE Standard 754, section 4. This is called rounding to nearest or sometimes bankers rounding.
It's just one of many ways to do rounding and they choose this one. See: http://en.wikipedia.org/wiki/Bankers_rounding
And for more information: Why does .NET use banker's rounding as default?
来源:https://stackoverflow.com/questions/15405667/decimal-round-default-setting-for-midpointrounding