Rounding It is a problem that occurs frequently in software development. I also use this operation in more than one project. C # If you search online, there will be a lot of results, but most of the content is Microsoft's Math. Round () Inaccuracy. It is a "four homes, six homes, and five into two". Then many people write their own methods to implement it. Some are very simple, some are very complicated, and some are not;
In fact, it is really not necessary to implement this function; since we know that C # has math. round (), didn't we find out how many eight overloaded methods it has? One of them is the parameter of the midpointrounding type, as long as we make good use of it, it is completely possible to achieve a very accurate rounding, there is no need to write such a complex method.
Midpointrounding: specifies how the mathematical rounding method processes the median between two numbers.
The following table shows the rounding results of some positive and negative numbers used in combination with the value of the midpointrounding. The precision used when rounding a number is zero, which means that the number after the decimal point will affect the rounding operation. For example, for the number-2.5, the number after the decimal point is 5. Because this number is an intermediate value, you can use the midpointrounding value to determine the rounding result. If awayfromzero is specified,-3 is returned because it is a number with zero precision and closest to zero. If toeven is specified,-2 is returned because it is the nearest even number with zero precision.
| Original number |
Take a value with a large absolute value |
Returns an even number. |
| 3.5 |
4 |
4 |
| 2.8 |
3 |
3 |
| 2.5 |
3 |
2 |
| 2.1 |
2 |
2 |
| -2.1 |
-2 |
-2 |
| -2.5 |
-3 |
-2 |
| -2.8 |
-3 |
-3 |
| -3.5 |
-4 |
-4 |
I don't need to explain it any more. If we want to round 3.455 to 3.46, we only need to use the followingCodeYou can
====================================
Math. Round (3.455, 2, midpointrounding. awayfromzero)
====================================
To from, http://www.peugeothome.com/bbs/showtopic-814.aspx