What are the methods for rounding in C#?
In C#, you can use the Math.Round() method to round a number. This method has multiple overloads, with the most common one accepting a double type parameter and returning a double type result. For example:
double num = 3.567;
double roundedNum = Math.Round(num); // 结果为4
In addition, you can also specify the number of decimal places to round to, for example:
double num = 3.567;
double roundedNum = Math.Round(num, 2); // 结果为3.57
In addition to the Math.Round() method, you can also use a custom rounding function to achieve the rounding functionality, such as:
public double CustomRound(double num)
{
return Math.Floor(num + 0.5);
}
double num = 3.567;
double roundedNum = CustomRound(num); // 结果为4