2009-11-24 154 views
155

我要的是这样的:格式化百分比值的小数?

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

哪里%%是格式提供或任何我期待的。 应该导致:Value: %85.26.

基本上,我需要它为WPF结合,但首先让我们解决了一般格式问题:

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

回答

345

使用P format string。这将通过文化的不同而不同:

String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture) 
+0

[看这里的巨大差异就像美国和法国的类型](http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx)如果以上因文化而异,是否有文化无关的“P”格式? – bonCodigo 2014-05-18 01:36:12

+0

@bonCodigo:如果您想要输出特定文化,请明确指定文化。 – 2014-05-19 13:18:37

3

如果你有一个很好的理由抛开文化相关的格式,并得到明确的控制权是否存在的价值和“%”之间的空间,以及是否“ %“是前导或尾随,您可以使用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) 
-7

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

String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture) 
+0

而且仍然错误,如果你想强制输入这么多,你可以把数字作为浮点数并添加百分号,因为替换代价高昂,在这种情况下不是非常有用“String.Format(”Value:{0:F2 }。“,0.8526 * 100)” – rekiem87 2016-06-29 22:59:12

+0

完全同意rekiem87 – Defkon1 2017-03-02 17:23:33