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
After using the Midpointrounding.awayfromzero overload, compare:
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)
This calculates the decimal 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
C # Math.Round () for Chinese rounding (RPM)