user4227915
user4227915

Reputation:

Show double as percentage without decimals with ToString method

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.

Upvotes: 4

Views: 5671

Answers (4)

Soner Gönül
Soner Gönül

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.

enter image description here

You can guaranteed to set PercentNegativePattern property as well for negative values.

Upvotes: 3

Tim Schmelter
Tim Schmelter

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

Shadow
Shadow

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

user743382
user743382

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

Related Questions