What is the purpose of Math.Round in C#?
The Math.Round function in C# is used to round a number. It takes a double type parameter and returns the closest integer or decimal according to certain rounding rules.
- If the decimal part is less than 0.5, the nearest integer is returned, which means rounding down.
- If the decimal part is greater than or equal to 0.5, then return the closest integer, i.e. round up.
- If the decimal part is equal to 0.5, round according to the current rounding mode.
The rounding mode can be specified by using the overload version of the Math.Round function. For example, you can specify the MidpointRounding.ToEven mode, which means that if the decimal part is exactly 0.5, it will be rounded to the nearest even number.
Here is an example of the Math.Round function:
double number = 3.7;
int roundedNumber = (int)Math.Round(number); // 返回4
In the example above, Math.Round rounds 3.7 to the nearest integer, which is 4, and then converts it to an integer type.