Many people mistakenly treat the math. Round function as a rounding function, and the result is often incorrect. In fact, math. Round adopts the internationally accepted banker rounding method.
Banker's rounding (banker rounding)AlgorithmThat is, four homes, six homes, and five shopping cart. In fact, this is also the IEEE Standard for rounding. Therefore, all IEEE-compliant languages should adopt this algorithm. this algorithm can be summarized as: "four homes six into five considerations, after five is non-zero into one, after five are all zero look parity, before five is the occasional house to go, before five is odd to go into one."
See the following example:
Math. Round (3.44, 1); // returns 3.4. 4
Math. Round (3.451, 1); // After returns 3.5, a non-zero entry
Math. Round (3.45, 1); // returns 3.4. After, check for parity.
Math. Round (3.75, 1); // After returns 3.8, check for parity. Before five, it is odd to enter one.
Math. Round (3.46, 1); // returns 3.5. six entries
If we want to implement our traditional rounding function, a relatively simple method is to add 0.0000000001 to the back of the number, a small number. because "after five is not zero, it can be ensured that 5 must enter one.
Of course, you can also write functions by yourself.Code:
Public static decimal unit = 0.0.1m
Static public decimal round (decimal D)
{
Return round (D, Unit)
}
Static public decimal round (decimal D, decimal unit)
{
Decimal Rm = D % unit;
Decimal result = D-RM;
If (Rm> = unit/2)
{
Result + = unit;
}
Return result;
}