如何将数字格式化为固定的小数位数(保留尾随零),其中位数由变量指定?
e.g.
int x = 3;
Console.WriteLine(Math.Round(1.2345M, x)); // 1.234 (good)
Console.WriteLine(Math.Round(1M, x)); // 1 (would like 1.000)
Console.WriteLine(Math.Round(1.2M, x)); // 1.2 (would like 1.200)
请注意,由于我想以编程方式控制位置数量,因此 string.Format 将不起作用(当然我不应该生成格式字符串):
Console.WriteLine(
string.Format("{0:0.000}", 1.2M)); // 1.200 (good)
我应该只包含 Microsoft.VisualBasic 并使用格式编号 http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.formatnumber(VS.80).aspx?
我希望这里遗漏了一些明显的东西。
Try
decimal x = 32.0040M;
string value = x.ToString("N" + 3 /* decimal places */); // 32.004
string value = x.ToString("N" + 2 /* decimal places */); // 32.00
// etc.
希望这对你有用。看
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
了解更多信息。如果您发现附加有点麻烦,请尝试:
public static string ToRoundedString(this decimal d, int decimalPlaces) {
return d.ToString("N" + decimalPlaces);
}
然后你就可以打电话
decimal x = 32.0123M;
string value = x.ToRoundedString(3); // 32.012;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)