固定小数位很容易
String.Format("{0:F1}", 654.321);
提供
654.3
如何像在C语言中一样将小数位数作为参数传递?
String.Format("{0:F?}", 654.321, 2);
提供
654.32
我找不到应该替换 ? 的内容。
固定小数位很容易
String.Format("{0:F1}", 654.321);
提供
654.3
如何像在C语言中一样将小数位数作为参数传递?
String.Format("{0:F?}", 654.321, 2);
提供
654.32
我找不到应该替换 ? 的内容。
需要格式化的字符串不一定是常量。
int numberOfDecimalPlaces = 2;
string formatString = String.Concat("{0:F", numberOfDecimalPlaces, "}");
String.Format(formatString, 654.321);
使用 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)));
NumberFormatInfo.CurrentInfo.Clone()
来保留当前CultureInfo的其余部分。 - GazTheDestroyerint prec = 2;
string.Format($"{{0:F{prec}}}", 654.321);
我认为虽然还是有些混乱,但更加方便了。请注意,字符串插值将双括号(如{{
)替换为单个括号。
对于格式化单个值,可能最有效的方法是:
int decimalPlaces= 2;
double value = Math.PI;
string formatString = String.Format("F{0:D}", decimalPlaces);
value.ToString(formatString);
我使用了两个插值字符串(一种迈克尔的答案的变体):
double temperatureValue = 23.456;
int numberOfDecimalPlaces = 2;
string temperature = $"{temperatureValue.ToString($"F{numberOfDecimalPlaces}")} \u00B0C";
我使用了一种类似于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}";
string.Format("{0:F2}", 654.321);
输出将会是
654.32