固定小数位很容易
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)));
另一种选择是使用像这样的插值字符串:
int 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);
我使用类似于 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}";
我使用了两个插值字符串(Michael 的答案的变体):
double temperatureValue = 23.456;
int numberOfDecimalPlaces = 2;
string temperature = $"{temperatureValue.ToString($"F{numberOfDecimalPlaces}")} \u00B0C";
使用自定义数字格式字符串链接
var value = 654.321;
var s = value.ToString("0.##");
使用
string.Format("{0:F2}", 654.321);
输出将是
654.32