When math. Round (1.25, 1) is used in C #, the expected result is 1.3.
1. because math. the round method does not follow the rounding principle, but uses the "four homes, six homes, and five into double" method, if "less than 5" or "greater than 5" is to be rounded to the back of the bit to be rounded up, It is rounded up in the general sense. if "5 is equal to the value after the number of digits to be rounded off", check whether the last digit is an even number or an odd number. For example:
Math. Round (1.25, 1) = 1.2 because the front of 5 is 2, which is an even number, the 5 is not carried.
Math. Round (1.35, 1) = 1.4 because 5 is preceded by 3 and is an odd number, so carry
And 0 is also regarded as an even number, So math. Round (0.5, 0) = 0
2. from a statistical point of view, "four homes, six homes, five into two" is more scientific than "four homes and five into five", which makes some of the results after rounding bigger, some smaller, more even. instead of rounding in five, the result tends to be large.
For example, if the value is 1.15 + 1.25 + 1.35 + 1.45 = 5.2, if the number is rounded to a decimal place
1.2 + 1.3 + 1.4 + 1.5 = 5.4
According to the calculation of "four homes, six into five into two", 1.2 + 1.2 + 1.4 + 1.4 = 5.2, the result after rounding better reflects the actual result 3. both C # And VB.net adopt the "four homes, six homes, and five into two" principle, while SQL Server is a simple "Rounding ".
However, if a single number is rounded off, this method obviously won't work, because math. round (0.5, 0) = 0, so you need to write another method to implement it. The following is the method used in our project for your reference: C # code
- Public staticdecimal round (decimal D, int decimals)
- {
- Decimal tenpow = convert. todecimal (math. Pow (10, decimals ));
- Decimal scrd = D * tenpow + 0.5 m;
- Return (convert. todecimal (math. Floor (convert. todouble (scrd)/tenpow );
- }
Public static decimal round (decimal D, int decimals) {decimal tenpow = convert. todecimal (math. pow (10, decimals); decimal scrd = D * tenpow + 0.5 m; Return (convert. todecimal (math. floor (convert. todouble (scrd)/tenpow );}
In addition, if the decimal point is long enough, you can use the decimal. Round method, for example:
Decimal. Round (1.25, 1) = 1.2
However, if it is decimal. Round (1.251, 1) = 1.3
So the following method can achieve rounding effect C # code
- Public staticdecimal mydecimalround (decimal D, int
Decimals)
- {
- D = d + 0.000000000000001 m;
- Return decimal. Round (D, decimals );
- }