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?
Round(Decimal, Int32) Method This method is used to round a Decimal value to a specified number of decimal places. Syntax: public static decimal Round (decimal d, int decimals); Parameters: d: It is a decimal number which is to be rounded.
Round(Double, Int32, MidpointRounding) This method is used to rounds a double precision floating-point value to a specified number of fractional digits. A parameter specifies how to round the value if it is midway between two numbers.
The Math. Round() method in C# rounds a value to the nearest integer or to the specified number of fractional digits.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With