C# 百分比值的格式小数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1790975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format decimal for percentage values?
提问by Shimmy Weitzhandler
What I want is something like this:
我想要的是这样的:
String.Format("Value: {0:%%}.", 0.8526)
Where %% is that format provider or whatever I am looking for.
Should result: Value: %85.26.
.
其中 %% 是那种格式提供者或我正在寻找的任何东西。应该结果:Value: %85.26.
。
I basically need it for wpf binding, but first let's solve the general formatting issue:
我基本上需要它来进行 wpf 绑定,但首先让我们解决一般的格式问题:
<TextBlock Text="{Binding Percent, StringFormat=%%}" />
采纳答案by Michael Haren
Use the P
format string. This will vary by culture:
使用P
格式字符串。这将因文化而异:
String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)
回答by Jon Schneider
If you have a good reason to set aside culture-dependent formatting and get explicit control over whether or not there's a space between the value and the "%", and whether the "%" is leading or trailing, you can use NumberFormatInfo's PercentPositivePatternand PercentNegativePatternproperties.
如果您有充分的理由搁置依赖于文化的格式并明确控制值和“%”之间是否有空格,以及“%”是前导还是尾随,您可以使用 NumberFormatInfo 的PercentPositivePattern和PercentNegativePattern属性。
For example, to get a decimal value with a trailing "%" and no space between the value and the "%":
例如,要获取带有尾随“%”且值和“%”之间没有空格的十进制值:
myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });
More complete example:
更完整的例子:
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)
回答by Ian Townsend
I have found the above answer to be the best solution, but I don't like the leading space before the percent sign. I have seen somewhat complicated solutions, but I just use this Replace addition to the answer above instead of using other rounding solutions.
我发现上述答案是最好的解决方案,但我不喜欢百分号前的前导空格。我已经看到了一些复杂的解决方案,但我只是在上面的答案中使用了这个 Replace 补充,而不是使用其他舍入解决方案。
String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)
回答by David Neira
If you want to use a format that allows you to keep the number like your entry this format works for me:
"# \\%"
如果你想使用一种允许你像条目一样保留数字的格式,这种格式对我有用:
"# \\%"
回答by Nitika Chopra
This code may help you:
此代码可以帮助您:
double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";