Requirements: Often used for rounding and not very sensitive to precision requirements.
To achieve rounding two decimal places, the developer wrote the following code,
The code is very simple, developersThe actual result was 12.12, which contradicted the expected rounding result of 12.13。
The reason for this result is that Math.Round does not use the rounding rule by default, but rather rounds to make even.
Round up to five to make a pair
The so-called rounding of six to five to make a pair means that after determining the significant digits, if the next significant digit is less than or equal to 4, it is rounded down; if it is greater than or equal to 6, round up by one. When the next significant digit is 5,
- If the number before 5 is odd, round up five and advance by one
- If 5 is before an even number, skip 5 (0 is even).
Statistically, rounding to even is more accurate than rounding five, because when there are many calculations, rounding every five to one can lead to a larger number.
For example:
1.15+1.25+1.35+1.45 = 5.2
If the significant digits are one decimal place, the result is obtained using the rounding principle
1.2 + 1.3 + 1.4 + 1.5 = 5.4
The result obtained by rounding to five evens is
1.2 + 1.2 + 1.4 + 1.4 = 5.2
This shows that the rounding rule yields more precise results.
Math.Round
So how do you use Math.Round to achieve the expected rounding?
In fact, Math.Round in C# provides many overloading methods, including two methods:
Both methods provide a third parameter called mode, which is an enumeration variable of MidpointRounding with two selectable values
- AwayFromZero - rounding up
- ToEven - rounding to even rounding
So if we want an ideal rounded result, we can use the following code:
MidpointRounding enumeration, as shown below:
Reference:The hyperlink login is visible. |