How to round in C#?
In C#, you can use the Math.Round() method to achieve rounding.
The Math.Round(double value) method takes a double type parameter and returns the closest integer or floating-point number to the parameter value. If the decimal part of the parameter value is greater than or equal to 0.5, it rounds up; if the decimal part is less than 0.5, it rounds down; if the decimal part is equal to 0.5, it rounds according to the even number rule.
Here is an example:
double x = 3.45;
double y = Math.Round(x); // 结果为 3
double z = 3.55;
double w = Math.Round(z); // 结果为 4
If you want to specify the number of decimal places to retain, you can use the Math.Round(double value, int decimals) method, where the second parameter specifies the number of decimal places to retain.
Here is an example:
double a = 3.456789;
double b = Math.Round(a, 2); // 结果为 3.46
Note that the Math.Round() method can also be used to round other numeric types such as decimal and float.