简体   繁体   中英

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

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:

 43.5% 

Would appreciate some advice on what I can do.

You need to either explicitly cast a value to a non-integer form, eg 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM