2010-07-09 59 views

回答

37

Math.Round Method (Decimal, Int32)

例子:

Math.Round(3.44, 1); //Returns 3.4. 
+6

请注意,默认情况下,C#使用可能不是你想要的“Banker's Rounding”,所以有一个方法重载Math.Round(decimal,int,MidpointRounding)来让你指定使用哪个舍入方法。例如。 TSQL使用“远离零”舍入,因此可能会给出与默认C#舍入不同的值。 – 2010-07-09 12:38:10

+0

感谢有价值的信息先生 – 2010-07-09 12:39:15

1

使用Math.Round到它送到小数。

1

限制浮点数的精度是一个SQL概念。 csharp中的十进制只意味着它会记住分配的精度。分配之前,您可以舍入到小数点后三位。 IE,Math.Round()

10

我假设你真的是格式化输出:

Console.WriteLine("{0:0.###}", value); 
1

要获得小数回用Math.Round与第二个参数指定小数点的数字。

decimal d = 54.9700M;  
decimal f = (Math.Round(d, 2)); // 54.97 

至获取数使用.ToString()的字符串表示Specifiying小数点为N3。这里的3是小数点我的回答

decimal d = 54.9700M;  
string s = number.ToString("N3"); // "54.97" 
1

部分是响应,另一部分仅仅是一个有趣的观点:

我常常想看到的变量作为prop/field。所以创建一个extension method来解决我的问题:

Tensao只是一个Enum有一个值有关。

public static class TensaoExtensions { 
     public static double TensaoNominal(this Tensao tensao) { 
      return Math.Round((double.Parse(EnumMapper.Convert(typeof(Tensao), 
          tensao.ToString()))) * 1000/Math.Sqrt(3), 3); 
     } 
    }