How to format a number as percentage without the percentage sign?

匆匆过客 提交于 2019-11-29 03:01:53

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.

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

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}" />

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*

HitLikeAHammer

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.

How about a trim?

double d = .102;
string percent = d.ToString("P0").Trim(' ', '%');

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, ...?

mtranda

You could also try something like

string newString = "0.13".Replace("0.", string.Empty) + "%";

Here is an example using NumberFormatInfo as @Richard suggested:

string.Format(new NumberFormatInfo { PercentSymbol = string.Empty }, "{0:0%}", 0.123); // => 12

Here is another shorter and cleaner way to do it.

$"{rate * 100:F2}"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!