C # math. Round () Achieves Chinese rounding
Math. Round () in C # does not use the "Rounding" method. In fact, in VB, VBScript, C #, J #, T-SQL in the round function are using banker's rounding (Banker algorithm), namely:Four Homes, six in five get even. In fact, this is also the IEEE standard, so all languages that comply with the IEEE Standard should adopt this algorithm.
Starting from. NET 2.0, the math. Round method provides an enumeration option, midpointrounding. awayfromzero, which can be used to implement "Rounding" in the traditional sense ". That is: Math. Round (4.5, midpointrounding. awayfromzero) = 5.
Round(Decimal)Round(Double)Round(Decimal, Int32)Round(Decimal, MidpointRounding)Round(Double, Int32)Round(Double, MidpointRounding)Round(Decimal, Int32, MidpointRounding)Round(Double, Int32, MidpointRounding)
For example:
Math. Round (0.4) // result: 0
Math. Round (0.6) // result: 1
Math. Round (0.5) // result: 0
Math. Round (1.5) // result: 2
Math. Round (2.5) // result: 2
Math. Round (3.5) // result: 4
Math. Round (4.5) // result: 4
Math. Round (5.5) // result: 6
Math. Round (6.5) // result: 6
Math. Round (7.5) // result: 8
Math. Round (8.5) // result: 8
Math. Round (9.5) // result: 10
Comparison after using the midpointrounding. awayfromzero overload:
Math. Round (0.4, midpointrounding. awayfromzero); // result: 0
Math. Round (0.6, midpointrounding. awayfromzero); // result: 1
Math. Round (0.5, midpointrounding. awayfromzero); // result: 1
Math. Round (1.5, midpointrounding. awayfromzero); // result: 2
Math. Round (2.5, midpointrounding. awayfromzero); // result: 3
Math. Round (3.5, midpointrounding. awayfromzero); // result: 4
Math. Round (4.5, midpointrounding. awayfromzero); // result: 5
Math. Round (5.5, midpointrounding. awayfromzero); // result: 6
Math. Round (6.5, midpointrounding. awayfromzero); // result: 7
Math. Round (7.5, midpointrounding. awayfromzero); // result: 8
Math. Round (8.5, midpointrounding. awayfromzero); // result: 9
Math. Round (9.5, midpointrounding. awayfromzero); // result: 10
But the tragedy is that if we use this to calculate decimal places, it will not work !!!
The seventh overload method must be used,
Decimal round (decimal D, int decimals, midpointrounding Mode)
The decimal number calculated in this way is the real Chinese Style rounding !!
?Math.Round(526.925, 2)526.92?Math.Round(526.925, 2,MidpointRounding.AwayFromZero)526.92?Math.Round((decimal)526.925, 2)526.92?Math.Round((decimal)526.925, 2,MidpointRounding.AwayFromZero)526.93