如何限制十进制数?
可能重复:
如何格式化小数
我怎样才能限制我的十进制数,这样我才能得到这个数字后的3位数?
eg 2.774
Math.Round方法(十进制,Int32)
例:
Math.Round(3.44, 1); //Returns 3.4.
我假设你真的是指为输出格式化它:
Console.WriteLine("{0:0.###}", value);
要获得Decimal,请使用Math.Round
其中第二个参数指定小数点数。
decimal d = 54.9700M; decimal f = (Math.Round(d, 2)); // 54.97
获取数字使用的字符串表示.ToString()
将小数点指定为N3。 其中3是小数点
decimal d = 54.9700M; string s = number.ToString("N3"); // "54.97"
限制浮点数的精度是SQL概念。 csharp中的十进制仅表示它将记住指定的精度。 在分配之前,您可以舍入到小数点后三位。 IE, Math.Round()
。
使用Math.Round
将其四舍五入到小数点后3位。
我的部分答案是答案,另一部分只是一个有趣的观点:
我经常希望将变量看作prop/field
。 所以创建一个extension method
来解决我的问题:
Tensao只是一个与价值相关的枚举。
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); } }