如何将数字格式化为固定数量的小数位(保持尾随零),其中位数由变量指定?
例如:
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并使用FormatNumber(http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.formatnumber(VS.80%29.aspx)?
我希望我在这里遗漏了一些明显的东西。
发布于 2009-04-14 20:30:10
试一试
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
了解更多信息。如果你觉得这个附加有点老生常谈,试试:
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;发布于 2009-04-14 20:35:57
尝试此方法可以动态创建您自己的格式字符串,而不必使用多个步骤。
Console.WriteLine(string.Format(string.Format("{{0:0.{0}}}", new string('0', iPlaces)), dValue))在步骤中
//Set the value to be shown
decimal dValue = 1.7733222345678M;
//Create number of decimal places
int iPlaces = 6;
//Create a custom format using the correct number of decimal places
string sFormat = string.Format("{{0:0.{0}}}", new string('0', iPlaces));
//Set the resultant string
string sResult = string.Format(sFormat, dValue);发布于 2009-04-14 20:30:16
有关格式字符串帮助,请参阅以下链接:
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
你想要这个:
Console.WriteLine(Math.Round(1.2345M, x).ToString("F" + x.ToString()));此外,如果需要,.ToString调用将为您循环,因此您可以跳过Math.Round调用,只需执行以下操作:
Console.WriteLine(1.2345M.ToString("F" + x.ToString()));https://stackoverflow.com/questions/749232
复制相似问题