我假设你的确是想要将其格式化以便于输出:
Console.WriteLine("{0:0.###}", value);
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"
Math.Round
将其四舍五入到3位小数。限制浮点数的精度是SQL概念。在C#中,Decimal仅表示它将记住分配的精度。您可以在分配之前四舍五入到三位小数。例如:Math.Round()
。
我的回答中包含了响应的部分和一些有趣的观点:
我经常想将变量视为一个属性/字段
。因此,我创建了一个扩展方法
来解决这个问题:
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);
}
}