1

I'm writing an ASP.Net MVC4 web application, and I want to calculate the size of some elements using C#.

However, I'm having some trouble because css will only accept percentages as xx.yy%, that is with a point as the decimal separator, and no space before the percent symbol (as far as I have discovered).

The problem is, I can't find any C# culture that produces this kind of percentages. It seems that English (US) produces the right decimal separator, while German uses the percent symbol correctly (from http://msdn.microsoft.com/en-us/library/shxtf045(v=vs.85).aspx)

Culture:                  English (United States)
(P) Percent:. . . . . . . -123,456.70 %
Culture:                  German (Germany)
(P) Percent:. . . . . . . -123.456,70%

Is there one Culture or NumberFormat that is recommended for this, or at least one that consistently works? Or do I need to write my own, and how would I go ahead to do that?

4

3 回答 3

2

您可以编写自定义扩展方法:

public static string ToPercentageString(this double d)
{
    return d.ToString("p", CultureInfo.InvariantCulture).Replace(" ", string.Empty);
}
于 2013-07-25T07:32:54.650 回答
1

试试这个:

double number = 0.8623;
Console.WriteLine(number.ToString("#0.##%"));

这应该产生 86.23%(带点,% 符号前没有空格)

于 2013-07-25T07:37:02.717 回答
0

您可以指定自己的自定义格式字符串:

using System.Globalization;
class Program {
    static void Main(string[] args) {
        double d = 12.345;
        string s = string.Format(CultureInfo.InvariantCulture, "{0:0.00}%", d);
    }
}

以下是数字格式字符串的一些输出示例:自定义数字格式字符串输出示例

于 2013-07-25T07:32:44.197 回答