How to format a number as percentage without the p

2020-02-10 02:01发布

How do I in .NET format a number as percentage without showing the percentage sign?

If I have the number 0.13 and use the format string {0:P0} the output is 13 %.

However I would like to get 13 instead, without having to multiply the number by 100 and using the format string {0:N0}.

(Background: In ASP.NET I have a GridView with a BoundField where I would like to display a number as percentage but without the percentage sign (%). How do I do that?)


Thanks for the answers. At the time of editing 4 out of 6 suggest what I would like to avoid, as explained above. I was looking for a way to use a format string only, and avoid multiplying by 100 and using {0:N0}, but the answers indicate that's impossible...


Solved by using the accepted solution by Richard:


public class MyCulture : CultureInfo
{
    public MyCulture()
        : base(Thread.CurrentThread.CurrentCulture.Name)
    {
        this.NumberFormat.PercentSymbol = "";
    }
}

Thread.CurrentThread.CurrentCulture = new MyCulture();

10条回答
淡お忘
2楼-- · 2020-02-10 02:58

How about this...

String.Format("{0:P0}",0.13).Replace("%","")

EDIT: This should work across cultures:

var percentSymbol = CultureInfo.CurrentCulture.NumberFormat.PercentSymbol;
String.Format("{0:P0}",0.13).Replace(percentSymbol,"")

There is also this solution which may be more elegant but slightly more code.

查看更多
做自己的国王
3楼-- · 2020-02-10 02:59

The MSDN* has this under "Custom Numeric Format Strings":

The presence of a '%' character in a format string causes a number to be multiplied by 100 before it is formatted. The appropriate symbol is inserted in the number itself at the location where the '%' appears in the format string. The percent character used is dependent on the current NumberFormatInfo class.

But the example shows that it also outputs the % sign - not what you want, but perhaps settable to nothing via the NumberFormatInfo class?

However, I agree with Pax and can't see why do don't go with the * 100 and {0:N0}

**Accessing from within Visual Studio so no link*

查看更多
家丑人穷心不美
4楼-- · 2020-02-10 02:59

You could also try something like

string newString = "0.13".Replace("0.", string.Empty) + "%";
查看更多
老娘就宠你
5楼-- · 2020-02-10 03:00

Why don't you just multiply the number by 100 and use your "{0:N0}" format string? That seems to me to be the easiest solution.

Unless you can come up with a viable reason why that's out of the question, that's my advice. It's not rocket science :-)

查看更多
登录 后发表回答