我可以仅使用格式字符串将浮点数显示为带有 positive/negative 符号的百分比值吗?

Can I display float as percent value with positive/negative sign just with formatting string?

例如,输入 0.12 应生成字符串“+12%”,-0.42 应生成“-42%”。我想在不编写任何实际代码的情况下实现它,仅通过定义格式字符串。

尝试:

using System;
using System.Globalization;

namespace PercentageTest {
    class Program {
        static void Main(string[] args) {
            double number = 0.12;
            Console.WriteLine("The percent format is as : +" + number.ToString("P", CultureInfo.InvariantCulture));
            double no = 0.04;
            Console.WriteLine("The percent format is as : +" + no.ToString("P", CultureInfo.InvariantCulture));
            double negNumber = -0.12;
            Console.WriteLine("The percent format is as : " + negNumber.ToString("P", CultureInfo.InvariantCulture));
        }
    }
}

你可以在这里玩: code here

您可以使用扩展方法:

public static class Extensions
{
    public static string ToPercentage(this double number)
    {
        number *= 100; 
        return $"{(number >= 0 ? '+' : "")}{number:N}%";            
    }
}

用法示例:

double number = 0.95;
string str = number.ToPercentage(); // output +95%
        
double number2 = -0.15;
string str2 = number2.ToPercentage(); // output -15%

您可以使用条件字符串格式:

public static void Main()
{
    string format = "+#.00 %;-#.00 %;+0.00 %";
    Console.WriteLine((-0.12).ToString(format));
    Console.WriteLine((0.12).ToString(format));
    Console.WriteLine(0.ToString(format));
}

输出:

-12.00 %
+12.00 %
+0.00 %

不幸的是,PercentPositivePattern 没有允许在应用程序范围内指定加号的值。