格式化百分比值的小数?
问题描述:
我要的是这样的:格式化百分比值的小数?
String.Format("Value: {0:%%}.", 0.8526)
哪里%%是格式提供或任何我期待的。 应该导致:Value: %85.26.
。
基本上,我需要它为WPF结合,但首先让我们解决了一般格式问题:
<TextBlock Text="{Binding Percent, StringFormat=%%}" />
答
使用P
format string。这将通过文化的不同而不同:
String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)
答
如果你有一个很好的理由抛开文化相关的格式,并得到明确的控制权是否存在的价值和“%”之间的空间,以及是否“ %“是前导或尾随,您可以使用NumberFormatInfo的PercentPositivePattern和PercentNegativePattern属性。
例如,为了获得一个十进制值与尾部的“%”和值与“%”之间没有空格:
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)
答
我有发现上面的答案是最好的解决方案,但我不喜欢百分号前的前导空格。我已经看到了一些复杂的解决方案,但是我只是在上面的答案中使用了这个Replace而不是其他舍入解决方案。
String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)
[看这里的巨大差异就像美国和法国的类型](http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx)如果以上因文化而异,是否有文化无关的“P”格式? – bonCodigo 2014-05-18 01:36:12
@bonCodigo:如果您想要输出特定文化,请明确指定文化。 – 2014-05-19 13:18:37