Original: C # in Math.Round () to achieve Chinese-style rounding
Math.Round () in C # to make Chinese-style rounding
Math.Round () in C # is not a "rounding" method used. In fact, in VB, VBScript, C #, J #, T-SQL round functions are used banker ' s rounding (banker algorithm), namely: four six into the five to take the pair . In fact, this is also an IEEE specification, so all IEEE compliant languages should adopt such an algorithm.
Starting with. NET 2.0, the Math.Round method provides an enumeration option Midpointrounding.awayfromzero can be used to implement "rounding" in the traditional sense. namely: 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)
Such as:
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
Use midpointrounding. Awayfromzero Post-reload comparison:
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 you use this to calculate the decimal, it will not be the spirit!!!
A seventh overloaded method must be used,
decimal Round (decimal D, int decimals, midpointrounding mode)
so the calculated decimal is the real Chinese-style rounding !!
? Math.Round (526.9252)526.92? Math.Round (526.9252, Midpointrounding.awayfromzero)526.92? Math.Round (decimal)526.9252)526.92? Math.Round ((decimal)526.9252, Midpointrounding.awayfromzero) 526.93
Math.Round () in C # to make Chinese-style rounding