C# Rounding Guide: Master Math.Round Method
In C#, you can achieve true rounding using the Math.Round method. The Math.Round method has multiple overloads, allowing you to specify the number of decimal places to round. For example, to round a double type number, you can use the following code:
double number = 3.567;
double roundedNumber = Math.Round(number, MidpointRounding.AwayFromZero);
Console.WriteLine(roundedNumber); // 输出4
In the code above, when the MidpointRounding.AwayFromZero parameter is specified, it means that rounding should be done away from zero when encountering a 5, essentially performing true rounding. If the MidpointRounding parameter is not specified, the default behavior is to use MidpointRounding.ToEven, where rounding towards the nearest even number occurs when encountering a 5.
Apart from specifying the MidpointRounding.AwayFromZero parameter, you can also specify the decimal places as shown below:
double number = 3.567;
double roundedNumber = Math.Round(number, 2, MidpointRounding.AwayFromZero);
Console.WriteLine(roundedNumber); // 输出3.57
This can achieve rounding the decimals to the nearest whole number.