C#中的MathF.Round()方法与示例
C#中的MathF.Round()方法用于将值四舍五入到最接近的整数或小数位数。
语法
以下是语法-
public static float Round (float x); public static float Round (float x, int digits); public static float Round (float x, int digits, MidpointRounding mode); public static float Round (float x, MidpointRounding mode);
示例
现在让我们看一个实现MathF.Round()方法的示例-
using System; public class Demo { public static void Main(){ float val1 = 15.20f; float val2 = 3.10f; Console.WriteLine("Rounded (val1) = "+MathF.Round(val1)); Console.WriteLine("Rounded (val2) = "+MathF.Round(val2)); } }
输出结果
这将产生以下输出-
Rounded (val1) = 15 Rounded (val2) = 3
示例
现在让我们来看另一个实现MathF.Round()方法的示例-
using System; public class Demo { public static void Main(){ float val1 = 10.23898f; float val2 = 20.878788f; Console.WriteLine("Rounded (val1) = "+MathF.Round(val1,2)); Console.WriteLine("Rounded (val2) = "+MathF.Round(val2,3)); } }
输出结果
这将产生以下输出-
Rounded (val1) = 10.24 Rounded (val2) = 20.879