十进制格式为百分比值?
-
22-09-2019 - |
题
我想是这样的:
String.Format("Value: {0:%%}.", 0.8526)
在哪里%%是格式提供或任何我期待的。
应导致:Value: %85.26.
基本上,我需要它为WPF结合,但首先让我们解决了一般格式问题:
<TextBlock Text="{Binding Percent, StringFormat=%%}" />
解决方案
使用 P
格式字符串。这将通过培养而异:
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)
如果你想使用的格式允许哟保持数像你entrie这种格式的工作对我来说:
"# \\%"
这代码可以帮助你:
double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";
我已经找到了上面的回答是最好的解决办法,但我不喜欢百分号前面有一个空格。我见过有些复杂的解决方案,但我只是用这个替换除了上述的答案,而不是使用其他的解决方案四舍五入
String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)
不隶属于 StackOverflow