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

Time:05-02

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.

CodePudding user response:

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.

CodePudding user response:

Try:

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

You can play with it here: code here

CodePudding user response:

You could use extension method :

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

usage example :

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