如何在C#中将十进制格式化为以编程方式控制的小数位数?

Mic*_*ren 7 c# string formatting

如何将数字格式化为固定数量的小数位(保留尾随零),其中位数由变量指定?

例如

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)
Run Code Online (Sandbox Code Playgroud)

请注意,因为我想以编程方式控制位数,所以这个string.Format将不起作用(当然我不应该生成格式字符串):

Console.WriteLine(
    string.Format("{0:0.000}", 1.2M));    // 1.200 (good)
Run Code Online (Sandbox Code Playgroud)

我应该只包含Microsoft.VisualBasic并使用FormatNumber吗?

我希望在这里遗漏一些明显的东西.

Nic*_*rdi 12

尝试

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.
Run Code Online (Sandbox Code Playgroud)

希望这对你有用.看到

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

欲获得更多信息.如果你发现附加有点hacky尝试:

public static string ToRoundedString(this decimal d, int decimalPlaces) {
    return d.ToString("N" + decimalPlaces);
}
Run Code Online (Sandbox Code Playgroud)

那你就可以打电话了

decimal x = 32.0123M;
string value = x.ToRoundedString(3);  // 32.012;
Run Code Online (Sandbox Code Playgroud)

  • 请注意:"F"和"N"之间的差异:"N"将插入千位分隔符,而"F"则不会. (2认同)

ste*_*ell 5

尝试此方法来动态创建您自己的格式字符串,而无需使用多个步骤。

Console.WriteLine(string.Format(string.Format("{{0:0.{0}}}", new string('0', iPlaces)), dValue))
Run Code Online (Sandbox Code Playgroud)

分步进行

//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);
Run Code Online (Sandbox Code Playgroud)