Coder Perfect

How should percentage figures be formatted in decimal?


What I’m looking for is something along these lines:

String.Format("Value: {0:%%}.", 0.8526)

Where %% is that format provider or whatever I am looking for. Should result: Value: %85.26..

I primarily require it for wpf binding, but first and foremost, let us address the general formatting issue:

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

Asked by Shimmy Weitzhandler

Solution #1

The P format string should be used. This will differ depending on the culture:

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

Answered by Michael Haren

Solution #2

You can utilize NumberFormatInfo’s PercentPositivePattern and PercentNegativePattern attributes to remove culture-dependent formatting and gain explicit control over whether or not there is a space between the value and the ” percent “, as well as whether the ” percent ” is leading or trailing.

To produce a decimal value with a trailing ” percent ” and no space between the value and the ” percent “, use the following formula:

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)

Answered by Jon Schneider

Solution #3

If you wish to use a format that keeps the number the same as your entry, I like this one: “# percent “

Answered by David Neira

Solution #4

This code may be of assistance to you:

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

Answered by Nitika Chopra

Solution #5

Set your “P” string format and culture.

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));


“P02: 72.95%”

“P01: 72.9%”

“P: 72.95%”

“P1: 72.9%”

“P3: 72.949%”

Answered by suleymanduzgun

Post is based on