Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show double as percentage without decimals with ToString method

Tags:

c#

tostring

Looking for:

95,4545454545455 -> 95 %

I tried using:

String resultAsPercentage = result.ToString("##0 %");

But, it shows

9545 %

Then, I solved my problem using regex:

enter image description here

Question: Why my ToString method hasn't worked? And how to fix it to avoid using regex?

Thanks in advance.


2 Answers

You can use thew P(ercentage) format specifier, you need to divide through 100 because the specifier multiplies it by 100:

decimal value = 95.4545454545455m;
String resultAsPercentage = (value / 100).ToString("P0");  // 95%

If you need the space between the value and the percentage symbol you could use this approach:

NumberFormatInfo nfi = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
nfi.PercentSymbol = " %";
String resultAsPercentage = (value / 100).ToString("P0", nfi);  // 95 %
like image 162
Tim Schmelter Avatar answered Sep 10 '25 20:09

Tim Schmelter


As documented on Custom Numeric Format Strings, the % modifier multiplies the value by 100 before inserting the %. It's intended to be used with fractions. To disable this special meaning of %, escape it by preceding it with @"\".

Alternatively, you could take the % out of the format string, and append it manually: result.ToString("##0") + " %".


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!