.NET字符串格式化程序中的可变小数位数?

31

固定小数位很容易

String.Format("{0:F1}", 654.321);

提供

654.3

如何像在C语言中一样将小数位数作为参数传递?

String.Format("{0:F?}", 654.321, 2);

提供

654.32

我找不到应该替换 ? 的内容。

9个回答

23

需要格式化的字符串不一定是常量。

int numberOfDecimalPlaces = 2;
string formatString = String.Concat("{0:F", numberOfDecimalPlaces, "}");
String.Format(formatString, 654.321);

1
唉!我以为这可能是答案。每个格式都需要额外的字符串连接似乎很可怕,但我想要么就这样,要么写自己的格式化程序。非常感谢。 - GazTheDestroyer

17

使用 NumberFormatInfo

Console.WriteLine(string.Format(new NumberFormatInfo() { NumberDecimalDigits = 2 }, "{0:F}", new decimal(1234.567)));
Console.WriteLine(string.Format(new NumberFormatInfo() { NumberDecimalDigits = 7 }, "{0:F}", new decimal(1234.5)));

2
谢谢!刚学到了一些我不知道的东西。你最好使用NumberFormatInfo.CurrentInfo.Clone()来保留当前CultureInfo的其余部分。 - GazTheDestroyer

3
另一种选择是使用类似这样的插值字符串:
int prec = 2;
string.Format($"{{0:F{prec}}}", 654.321);

我认为虽然还是有些混乱,但更加方便了。请注意,字符串插值将双括号(如{{)替换为单个括号。


1

对于格式化单个值,可能最有效的方法是:

int decimalPlaces= 2;
double value = Math.PI;
string formatString = String.Format("F{0:D}", decimalPlaces);
value.ToString(formatString);

1

我使用了两个插值字符串(一种迈克尔的答案的变体):

double temperatureValue = 23.456;
int numberOfDecimalPlaces = 2;

string temperature = $"{temperatureValue.ToString($"F{numberOfDecimalPlaces}")} \u00B0C";

1

我使用了一种类似于Wolfgang答案的插值字符串方法,但更加简洁和易读(在我看来):

using System.Globalization;
using NF = NumberFormatInfo;

...

decimal size = 123.456789;  
string unit = "MB";
int fracDigs = 3;

// Some may consider this example a bit verbose, but you have the text, 
// value, and format spec in close proximity of each other. Also, I believe 
// that this inline, natural reading order representation allows for easier 
// readability/scanning. There is no need to correlate formats, indexes, and
// params to figure out which values go where in the format string.
string s = $"size:{size.ToString("N",new NF{NumberDecimalDigits=fracDigs})} {unit}";

0
另一种具有短插值字符串变体的定点格式:
var value = 654.321;
var decimals = 2;

var s = value.ToString($"F{decimals}");

-1

使用自定义数字格式字符串链接

var value = 654.321;
var s = value.ToString("0.##");

-3
使用
string.Format("{0:F2}", 654.321);

输出将会是

654.32


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接