Format decimal for percentage values?

Viewed 233002

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=%%}" />
7 Answers

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

Set your culture and "P" string format.

CultureInfo ci = new CultureInfo("en-us");
double floating = 72.948615;

Console.WriteLine("P02: {0}", (floating/100).ToString("P02", ci)); 
Console.WriteLine("P01: {0}", (floating/100).ToString("P01", ci)); 
Console.WriteLine("P: {0}", (floating/100).ToString("P", ci)); 
Console.WriteLine("P1: {0}", (floating/100).ToString("P1", ci));
Console.WriteLine("P3: {0}", (floating/100).ToString("P3", ci));

Output:

"P02: 72.95%"

"P01: 72.9%"

"P: 72.95%"

"P1: 72.9%"

"P3: 72.949%"

This code may help you:

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

You can also use a "%" custom specifier and manually control the sign position. https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#SpecifierPct

A percent sign (%) in a format string causes a number to be multiplied by 100 before it is formatted. The localized percent symbol is inserted in the number at the location where the % appears in the format string.

string.Format("{0:0.0%}", 0.6493072393590115)
// outputs 64.9%
string.Format("{0:%000}", 0.6493072393590115)
// outputs %065
Related