Home > Article > Backend Development > Round floating point numbers using Math.Round function in C#
Using the Math.Round function in C# to round floating point numbers requires specific code examples
In the C# programming language, sometimes we need to round floating point numbers Rounding operation. At this time, we can use the Math.Round function to achieve this function.
Math.Round function is a built-in function in C# used for mathematical calculations. Its main function is to round the specified floating point number. The following is the common format of the Math.Round function:
Math.Round(double value); // Rounding double type values
Math.Round(decimal value); // Rounding decimal type values Value rounding
The value here is the floating point number that needs to be rounded. The Math.Round function will judge based on the decimal part of the value. If the decimal part is less than 0.5, it will be rounded down. If the decimal part is greater than or equal to 0.5, it will be rounded up.
The following is a specific code example:
using System; class Program { static void Main() { double number = 3.14159; double roundedNumber = Math.Round(number); Console.WriteLine("原数:" + number); Console.WriteLine("四舍五入后的数:" + roundedNumber); decimal decimalNumber = 6.789; decimal roundedDecimalNumber = Math.Round(decimalNumber); Console.WriteLine("原数:" + decimalNumber); Console.WriteLine("四舍五入后的数:" + roundedDecimalNumber); } }
In the above code, we define a double type variable number and a decimal type variable decimalNumber, which are assigned values of 3.14159 and 6.789 respectively. Next, we use the Math.Round function to round these two variables, and assign the results to the variables roundedNumber and roundedDecimalNumber respectively. Finally, we use the Console.WriteLine function to output the original number and the rounded number.
When we run the above code, we will get the following output:
Original number: 3.14159
Rounded number: 3
Original number: 6.789
Number after rounding: 7
As can be seen from the above output, the Math.Round function successfully rounded the floating point number and obtained the correct result.
Summary:
By using the Math.Round function in C#, we can easily round floating point numbers. The Math.Round function in the code example is simple to use. You only need to pass in the floating point number that needs to be rounded, and you can get the rounded result. When we need to round floating-point numbers in actual development, we can consider using the Math.Round function to simplify our code.
The above is the detailed content of Round floating point numbers using Math.Round function in C#. For more information, please follow other related articles on the PHP Chinese website!