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

zyfwsgd6  于 2023-10-21  发布在  .NET
关注(0)|答案(9)|浏览(138)

固定小数位很容易

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

654.3

我如何像在C中一样将小数位数作为参数输入?所以

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

654.32

我找不到应该替换的东西?

t1rydlwq

t1rydlwq1#

要格式化的字符串不必是常量。

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

xhv8bpkk2#

使用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)));
euoag5mw

euoag5mw3#

另一种选择是使用像这样的插值字符串:

int prec = 2;
string.Format($"{{0:F{prec}}}", 654.321);

还是一团糟,但更方便IMHO。请注意,字符串插值将双大括号(如{{)替换为单大括号。

wwwo4jvm

wwwo4jvm4#

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

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

i34xakig5#

我使用了一种类似于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}";
b4wnujal

b4wnujal6#

我使用了两个插值字符串(Michael的答案的变体):

double temperatureValue = 23.456;
int numberOfDecimalPlaces = 2;

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

6vl6ewon7#

另一种带有短interpolated string变体的定点格式:

var value = 654.321;
var decimals = 2;

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

sq1bmfud8#

使用自定义数字格式字符串Link

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

esyap4oy9#

使用

string.Format("{0:F2}", 654.321);

输出将
654.32

相关问题