Reputation:
Looking for:
95,4545454545455 -> 95 %
I tried using:
String resultAsPercentage = result.ToString("##0 %");
But, it shows
9545 %
Then, I solved my problem using regex:
Question: Why my ToString
method hasn't worked? And how to fix it to avoid using regex?
Thanks in advance.
Upvotes: 4
Views: 5671
Reputation: 98750
One way can be Clone
a culture (like InvariantCulture
), set it's PercentPositivePattern
to 0
, divide your value by 100
and get it's string representation using The percent ("P"
) format specifier with 0
precision and that cloned culture as;
var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.PercentNegativePattern = 0;
Console.WriteLine(((int)95.4545454545455 / 100.0).ToString("P0", clone)); // 95 %
You can see all associated patterns on Remarks section on that page.
You can guaranteed to set PercentNegativePattern
property as well for negative values.
Upvotes: 3
Reputation: 460068
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 %
Upvotes: 4
Reputation: 4006
If you don't care about rounding, you can use the following:
double result = 95.4545454545;
String resultAsPercentage = (int)result + " %";
System.out.println(resultAsPercentage);
Output is: 95 %
Casting to an int drops the decimal places without rounding
Upvotes: 3
Reputation:
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") + " %"
.
Upvotes: 3