How is the Math.Round function used in C#?
In C#, the Math.Round() method is used to round a floating-point number to the nearest integer or specified number of decimal places.
The Math.Round() method has multiple overloaded forms:
- Round(double): Round the floating-point number to the nearest integer.
- Round(double, MidpointRounding): Rounds a floating point number to the nearest integer, with the option to specify the rounding rule (MidpointRounding enumeration type).
- Round(double, int): Rounding a floating-point number to a specified number of decimal places.
- Round(decimal): to round a decimal number to the nearest whole number.
- Round(decimal, MidpointRounding) function: Rounds a decimal number to the nearest integer, with the option to specify the rounding rule.
- Round(decimal, int): Round the decimal number to the specified number of decimal places.
Here are some example usages:
double number = 3.14;
int roundedNumber = (int)Math.Round(number); // 结果为3
double number2 = 3.56;
int roundedNumber2 = (int)Math.Round(number2, MidpointRounding.AwayFromZero); // 结果为4
double number3 = 3.14159;
double roundedNumber3 = Math.Round(number3, 2); // 结果为3.14
decimal number4 = 3.14m;
int roundedNumber4 = (int)Math.Round(number4); // 结果为3
decimal number5 = 3.56m;
int roundedNumber5 = (int)Math.Round(number5, MidpointRounding.AwayFromZero); // 结果为4
decimal number6 = 3.14159m;
decimal roundedNumber6 = Math.Round(number6, 2); // 结果为3.14
It should be noted that the Math.Round() method returns a float or decimal number, and if you need to convert it to an integer, you can use (int) or Convert.ToInt32(). Furthermore, when using rounding rules, MidpointRounding.AwayFromZero means rounding to the nearest integer, while MidpointRounding.ToEven means rounding to the nearest even number.