There is no rounding function in C#, and no rounding function in programming languages, because the rounding algorithm is unscientific, and the Banker rounding method is internationally popular.
Bankers rounding algorithm, that is, rounding six into five into two, and picking up the two. In fact, this is also the rounding standard stipulated by IEEE. Therefore, all languages that comply with the IEEE standard should use this algorithm.
The default method is Banker rounding method
There are several overloaded methods in .NET 2.0
(Decimal, MidpointRounding) (Double, MidpointRounding) (Decimal, Int32, MidpointRounding) (Double, Int32, MidpointRounding)
Round the decimal value to the specified precision. MidpointRounding parameter, specify how to round this value when one value is exactly in the middle of another two numbers
This parameter is a MidpointRounding enum
This enum has two members, and the description in MSDN is:
AwayFromZero When a number is the intermediate value of the other two numbers, it is rounded to a value with a smaller absolute value among the two values.
ToEven When a number is the intermediate value of the other two numbers, it is rounded to the closest even number.
Notice! The explanation here is wrong! Actually rounded to the value with the greater absolute value of the two values. However, the example in MSDN is correct, the original English description is it is rounded towards the nearest number that is away from zero.
Therefore, to implement the rounding function, for positive numbers, you can add a parameter to specify that when a number is the intermediate value of the other two numbers, it is rounded to the value with a larger absolute value among the two values, for example:
(3.45, 2, )
However, the method above for negative numbers is wrong
Therefore, you need to write a function to handle it yourself
The first function:
double Round(double value, int decimals) { if (value < 0) { return (value + 5 / (10, decimals + 1), decimals, ); } else { return (value, decimals, ); } }
The second function:
double Round(double d, int i) { if(d >=0) { d += 5 * (10, -(i + 1)); } else { d += -5 * (10, -(i + 1)); } string str = (); string[] strs = ('.'); int idot = ('.'); string prestr = strs[0]; string poststr = strs[1]; if( > i) { poststr = (idot + 1, i); } string strd = prestr + "." + poststr; d = (strd); return d; }
Parameters: d represents the number to be rounded; i represents the number after the decimal point to be retained.
The second method is to round both positive and negative numbers, the first method is to round positive numbers, and the negative numbers are to round six.
Note: I personally believe that the first method is suitable for handling currency calculations, while the second method is suitable for displaying data statistics.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.