Search code examples
c#string-formatting

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


For example, input 0.12 should produce string "+12%" and -0.42 should produce "-42%". I'd like to achieve it without writing any actual code, only by defining format string.


Solution

  • You can use conditional string formating:

    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));
    }
    

    which outputs:

    -12.00 %
    +12.00 %
    +0.00 %
    

    Unfortunately there is no value for PercentPositivePattern that allows to specify a plus sign application wide.