Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

calculating a percentage

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
GB
Hello,

I am trying to caluclate the percentage, i am doing

float percentage;
float number1;
float number2;

percentage = (number1 / number2) * 100;

However percentage is always 0 because it is not giving me the answer to 2 dp. I know you can use cout << setprecision(2) << percentage << endl;
but i am not outputting percentage straight away - i am passing the variable to another function before outputting.

Any ideas on how to solve this?
Thanks for your help
jim
 
well instead of the decimal... why not multiply it by 100 first?

(number1*100)/number2

then you could manipulate it as you wanted.

Matt
 
Have you checked what numbers you are putting in for number1 and number2? It is possible that these aren't set correctly.
 
To round the number to 2 decimal places do this:

percentage = ( floor((number1 / number2) * 100 + .5 ) ) / 100;

which for 2/3 (.66666666...) will give you .67 . If you simply want 67, then omit the &quot;/100&quot;.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top