jsiklie
jsiklie

Reputation: 31

Decimal to Percentage formatter

I'm using this format {0:P2} it is returning proper value but the problem is it is giving space between value and % symbol. how do i remove that space?

Example :

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

I Want to remove space between 85.26 and % symbol.

Upvotes: 0

Views: 463

Answers (4)

Omar
Omar

Reputation: 16621

What about:

//using System.Globalization;
string result = String.Format(CultureInfo.InvariantCulture, "Value: {0:0.00%}", 0.8526); //85.26% 

Upvotes: 1

Martin Liversage
Martin Liversage

Reputation: 106956

The formatting of a percent value is controlled by the NumberFormatInfo used when formatting the value. To be more specific, the NumberFormatInfo.PercentPositivePattern controls the formatting and for you the value of that property is 0 leading to the pattern n % but you want to use 1 instead resulting in n%. In your case, because you do not specify a CultureInfo or NumberFormatInfo when formatting the value, you are using the current culture for formatting (the culture set by the user in Windows). You can make a clone of this and modify it:

var cultureInfo = CultureInfo.CurrentCulture;
var numberFormat = (NumberFormatInfo) cultureInfo.NumberFormat.Clone();
numberFormat.PercentPositivePattern = 1;
var result = String.Format(numberFormat, "Value: {0:P2}.", 0.8526);

To format negative numbers you will have to modify NumberFormatInfo.PercentNegativePattern accordingly.

Upvotes: 1

Ric
Ric

Reputation: 13258

string ret = "Value: " + String.Format("{0:P2}.", 0.8526).Replace(" ", "");

Returns: Value: 85.26%.

Upvotes: 0

Jacob Lambert
Jacob Lambert

Reputation: 7677

A long way to do it would be:

String formatedPercent = String.Format("{0:P2}",0.8526);
String[] splitFormated = formatedPercent.Split(" ");
Sting output = "Value: " + splitFormated[0] + splitFormated[1];

Returns "Value: 85.26%"

Upvotes: 0

Related Questions