What is the method to round up or down in C#?

In C#, you can use the Math.Round() method to round a number to the nearest integer. This method takes two parameters: the number to be rounded and the number of decimal places to retain. Here is an example code snippet of using the Math.Round() method for rounding to the nearest integer.

double number = 3.14159;
int roundedNumber = (int)Math.Round(number); // 结果为3

double number2 = 3.6;
int roundedNumber2 = (int)Math.Round(number2); // 结果为4

double number3 = 3.14159;
double roundedNumber3 = Math.Round(number3, 2); // 结果为3.14

In the first example, round 3.14159 to the nearest whole number as 3. In the second example, round 3.6 to the nearest whole number as 4. In the third example, round 3.14159 to two decimal places as 3.14.

bannerAds