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条回答
Juvenile、少年°
2楼-- · 2020-02-10 02:36

How about a trim?

double d = .102;
string percent = d.ToString("P0").Trim(' ', '%');
查看更多
beautiful°
3楼-- · 2020-02-10 02:38

A points to consider first, a percentage displayed without a % is a number so lets ignore the percentage aspect. You want to know how to display a number that's 1 or less as 100 or less. I appreciate that it's bound so you can't modify it at display time so why not modify it at query time, i.e. SELECT (value*100) AS Percentage, ...?

查看更多
小情绪 Triste *
4楼-- · 2020-02-10 02:39

Here is an example using NumberFormatInfo as @Richard suggested:

string.Format(new NumberFormatInfo { PercentSymbol = string.Empty }, "{0:0%}", 0.123); // => 12
查看更多
混吃等死
5楼-- · 2020-02-10 02:43

but multiplying by 100 is exactly what you want!

protected void myGrdiView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        myObjectType ot = (myObjectType)e.Row.DataItem;

        ot.myNumber = ot.myNumber * 100; // multiply by 100
    }
}

and in the HTML

<asp:BoundField DataType="myNumber" HeaderText="%" StringFormat="{0:N0}" />
查看更多
劳资没心,怎么记你
6楼-- · 2020-02-10 02:46

Define a custom culture with its own NumberFormatInfo which returns String.Empty for its PercentSymbol property.

Then use that custom culture for impacted pages (or for the whole application). This could be done by cloning from the default so other regional settings are preserved.

查看更多
干净又极端
7楼-- · 2020-02-10 02:48

Here is another shorter and cleaner way to do it.

$"{rate * 100:F2}"
查看更多
登录 后发表回答