This article is a mirror article of machine translation, please click here to jump to the original article.

View: 1|Reply: 0

[Tips] .NET/C# uses Math.Round's MidpointRounding for rounding

[Copy link]
Posted on46 seconds ago | | | |
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.




Previous:WITH (NOLOCK) optimization for high-concurrency EF Core queries
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com