I'm having a little problem with the formatting of numbers to 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 return:
0,0625%
1%
1,25%
1,66%
2,5%
5%
I am trying the following
NumberFormatInfo formato = new NumberFormatInfo();
formato.PercentDecimalDigits = 4;
numero.ToString("p",formato);
But this way, I am getting the following:
0,06250%
1,00000%
1,25000%
1,66000%
2,50000%
5,00000%
What would be the correct way to format it?
I managed to fix it thanks to laith 's answer .
I translate it so that it can be useful to someone
The symbol
%
is the notation used to multiply the number by100
and add the percent symbol.Use
P
is a shorter notation, but%
allows you to customize the outputTherefore, the formatting of the
string
is the same as always, but only the symbol is added%
at the end.Use the ToString with e.g. Here I give you an example
The results are like this:
I made a small extension that is more comfortable for me to use, with the
string
literals, then it is more difficult for me to read the code.I'll leave it in case it's useful to someone!
It is used as
decimal.ToStringP("#");
With#
as many decimals as needed, or asdecimal.ToStringP("2")
, with the2
also representing the number of decimals.