Format percentage in C #

3

I'm having a little problem with formatting numbers by percentage, I have a List<decimal> that has these elements

0.006250
0.010000
0.012500
0.016600
0.025000
0.050000

I intend to get back:

0,0625%
1%
1,25%
1,66%
2,5%
5%

I'm trying the following

NumberFormatInfo formato = new NumberFormatInfo();
formato.PercentDecimalDigits = 4;

numero.ToString("p",formato);

But in this way, I am receiving the following:

0,06250%
1,00000%
1,25000%
1,66000%
2,50000%
5,00000%

What would be the correct way to format it?

    
asked by Juan Salvador Portugal 03.09.2018 в 20:19
source

3 answers

5

Please fix this thanks to the answer from laith .

I translate it so that it can be useful to someone

double value1 .92;
double value2 .923;
string formatted1 = $"{value:0.#%}"; // "92%" 
string formatted2 = $"{value:0.#%}"; // "92.3%"

The % symbol is the notation used to multiply the number by 100 and add the percent symbol.

Using P is a shorter notation, but % allows you to customize the output

Therefore, the formatting of string is the same as always, but only the symbol % is added to the end.

    
answered by 03.09.2018 / 20:48
source
1

Use the ToString with p. Here I give you an example

decimal jose = 0.0125m;
Console.WriteLine(jose.ToString("p02"));
Console.WriteLine(jose.ToString("p01"));
Console.WriteLine(jose.ToString("p03"));
Console.WriteLine(jose.ToString("p0"));

The results are like this:

1.25%
1.3%
1.250%
1%
    
answered by 04.09.2018 в 21:38
0

I made a small extension that is more comfortable to use, with the string literal, then it is harder to read the code.

I'll leave it in case it's useful to someone!

public static string ToStringP(this decimal s, string format)
{
    int n;
    if( ! format.ToUpper().Any(x => x != '#') ) 
    {
        var f = $"0:0.{new String('#', format.Count(x => x == '#'))}%";
        return string.Format("{" + f + "}", s);
    }
    else if ( int.TryParse(format,out n))
    {
        var f = $"0:0.{new String('#', n)}%";
        return string.Format("{" + f + "}", s);
    }           
    else
    {
        throw new Exception("Uso invalido de la extensión");
    }
}

Use how decimal.ToStringP("#"); With as many # as decimals as needed, or as decimal.ToStringP("2") , with 2 also representing the number of decimals.

    
answered by 04.09.2018 в 20:23