Format decimal for percentage values?

本秂侑毒 提交于 2019-11-26 09:19:30

问题


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..

I basically need it for wpf binding, but first let\'s solve the general formatting issue:

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

回答1:


Use the P format string. This will vary by culture:

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



回答2:


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 PercentPositivePattern and PercentNegativePattern properties.

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)



回答3:


If you want to use a format that allows yo keep the number like your entrie this format work for me: "# \\%"




回答4:


This code may help you:

double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";



回答5:


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.

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


来源:https://stackoverflow.com/questions/1790975/format-decimal-for-percentage-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!