How can I get a percentage to 1 decimal place as a string when I divide two integers?

4263 views c#

Here's what I am using right now:

 var pc = (p * 100/ c).ToString();

Both p and c are integers but I am not sure how to get the answer as for example something like:


Would appreciate some advice on what I can do.

answered question

This should be enough for percentage formatting: pc.ToString("P1").

2 Answers


You need to either explicitly cast a value to a non-integer form, e.g. double, or use a non-integer in the calculation.

For example:

var pc = (p * 100/ (double)c).ToString();

or this (not 100.0 rather than 100):

var pc = (p * 100.0/ c).ToString();

Next you need to round the result:

var pc = Math.Round(p * 100 / (double)c, 1).ToString();

But as Tetsuya states, you could use the P1 format string (which would output something like 5.0% - culture dependent - for p = 5, c = 100):

var pc = (p / (double)c).ToString("P1");

posted this

In your case, p and c both are integers, so result variable will be also integer. Here, you have to use float or double or conversion to float or double, so you can get decimal point.

Add below code to get 1 decimal place.

string s = string.Format("{0:0.#}", pc);

posted this

Have an answer?


Please login first before posting an answer.