How can you round in C#?
In C#, you can use the Math.Round() function to perform rounding. One commonly used method of Math.Round() accepts a double type parameter and returns the closest integer. If the decimal part is greater than or equal to 0.5, it returns the next whole number or the same number if already a whole number; if the decimal part is less than 0.5, it returns the previous whole number.
Here is a sample code:
double number = 3.14159;
int roundedNumber = (int)Math.Round(number);
Console.WriteLine(roundedNumber); // 输出:3
number = 3.7;
roundedNumber = (int)Math.Round(number);
Console.WriteLine(roundedNumber); // 输出:4
number = 3.5;
roundedNumber = (int)Math.Round(number);
Console.WriteLine(roundedNumber); // 输出:4
number = 3.2;
roundedNumber = (int)Math.Round(number);
Console.WriteLine(roundedNumber); // 输出:3
In the above code, we pass a floating point number to the Math.Round() function and then convert the return value to an integer type, achieving the rounding effect.