226

我想要的是这样的:

String.Format("Value: {0:%%}.", 0.8526)

其中 %% 是该格式提供程序或我正在寻找的任何内容。应该结果:Value: %85.26.

我基本上需要它来进行 wpf 绑定,但首先让我们解决一般格式问题:

<TextBlock Text="{Binding Percent, StringFormat=%%}" />
4

6 回答 6

460

使用P格式字符串。这将因文化而异:

String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)
于 2009-11-24T15:56:01.073 回答
18

如果您有充分的理由搁置与文化相关的格式并明确控制值和“%”之间是否有空格,以及“%”是前导还是尾随,您可以使用 NumberFormatInfo 的PercentPositivePatternPercentNegativePattern属性。

例如,要获取一个尾随“%”且值与“%”之间没有空格的十进制值:

myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });

更完整的例子:

using System.Globalization; 

...

decimal myValue = -0.123m;
NumberFormatInfo percentageFormat = new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 };
string formattedValue = myValue.ToString("P2", percentageFormat); // "-12.30%" (in en-us)
于 2015-06-08T20:20:19.010 回答
6

如果您想使用一种允许您保留数字的格式,就像您的条目一样,这种格式适用于我: "# \\%"

于 2018-07-27T22:53:09.800 回答
5

此代码可以帮助您:

double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";
于 2019-06-22T10:06:02.297 回答
5

设置您的文化和“P”字符串格式。

CultureInfo ci = new CultureInfo("en-us");
double floating = 72.948615;

Console.WriteLine("P02: {0}", (floating/100).ToString("P02", ci)); 
Console.WriteLine("P01: {0}", (floating/100).ToString("P01", ci)); 
Console.WriteLine("P: {0}", (floating/100).ToString("P", ci)); 
Console.WriteLine("P1: {0}", (floating/100).ToString("P1", ci));
Console.WriteLine("P3: {0}", (floating/100).ToString("P3", ci));

输出:

“P02:72.95%”

“P01:72.9%”

“P:72.95%”

“P1:72.9%”

“P3:72.949%”

于 2021-03-31T07:55:20.743 回答
-9

我发现上面的答案是最好的解决方案,但我不喜欢百分号前的前导空格。我见过有些复杂的解决方案,但我只是在上面的答案中使用了这个 Replace 补充,而不是使用其他舍入解决方案。

String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)
于 2015-12-02T14:34:14.473 回答