Math. Round and rounding in. net

Source: Internet
Author: User

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;

}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.