C#中的Math.Round()方法
C#中的Math.Round()方法将值四舍五入为最接近的整数或指定的小数位数。
方法
以下是Math.Round()重载的方法-
Math.Round(Double) Math.Round(Double, Int32) Math.Round(Double, Int32, MidpointRounding) Math.Round(Double, MidpointRounding) Math.Round(Decimal) Math.Round(Decimal, Int32) Math.Round(Decimal, Int32, MidpointRounding) Math.Round(Decimal, MidpointRounding)
示例
现在让我们看一个实现Math.Round()方法的示例,即Math.Round(Decimal)-
using System; public class Demo { public static void Main(){ Decimal val1 = 78.12m; Decimal val2 = 30.675m; Console.WriteLine("Decimal Value = " + val1); Console.WriteLine("Rounded value = " + Math.Round(val1)); Console.WriteLine("Decimal Value = " + val2); Console.WriteLine("Rounded value = " + Math.Round(val2)); } }
输出结果
这将产生以下输出-
Decimal Value = 78.12 Rounded value = 78 Decimal Value = 30.675 Rounded value = 31
示例
我们来看另一个实现Math.Round()方法的示例,即Math.Round(Double)-
using System; public class Demo { public static void Main(){ Double val1 = 23.10; Double val2 = 90.98; Console.WriteLine("Double Value = " + val1); Console.WriteLine("Rounded value = " + Math.Round(val1)); Console.WriteLine("Double Value = " + val2); Console.WriteLine("Rounded value = " + Math.Round(val2)); } }
输出结果
这将产生以下输出-
Double Value = 23.1 Rounded value = 23 Double Value = 90.98 Rounded value = 91