124697
124697

Reputation: 21893

I can not divide two numbers correctly

int percent = (score/numberOfQuestions)*100;
progressText.setText(score+"/"+numberOfQuestions+"  "+percent+"%");

returns 0% no matter what I tired. I tried casting it to int, double, float

Why does it return 0% for a number like score=5 numberOfQuestions=8?

Upvotes: 10

Views: 51449

Answers (6)

Fritz
Fritz

Reputation: 10055

You're using an int (integer) to store that percentage. Try using float or double instead making score and number of questions float or double too (Thanks for teh comments, I totally skipped this...). If you have issues showing the value, I suggest you use DecimalFormat to format it.

Rather than using pure int math to calculate and store the percentage, I suggest this other alternatives if you want to have decimals in your result.

Upvotes: 2

Joe Greer
Joe Greer

Reputation: 19

score/numberOfQuestions will always provide a number between 0 and 1. You have two choices depending upon how accurate you need your computation. For most things, you can change the expression to (score * 100)/numberOfQUestions. This will give you two digits of accuracy. A problem would occur if score * 100 overflowed an int. Given your variable names, I doubt this would happen in this case. The second possibility would be to convert the expression to double for the computation.

Upvotes: 1

Victor Mukherjee
Victor Mukherjee

Reputation: 11045

int percent=(int)(((double)score/numberOfQuestions)*100);

Upvotes: 0

323go
323go

Reputation: 14274

Check your integer math. Your code won't work without casting for small values, so just move the operations around:

int percent = 100*score/numberOfQuestions;

Upvotes: 3

LeeNeverGup
LeeNeverGup

Reputation: 1114

The problem is that divide two integers gives you the integer part of the result. So, (score/numberOfQuestions) will be always 0.
What you should do is

int percent = (score * 100 / numberOfQuestions);

Then the *100 will be executed first, then the divide will give you correct result.

Upvotes: 15

Rohit Jain
Rohit Jain

Reputation: 213351

You need to cast on either of them: -

float percent = ((float)score/numberOfQuestions)*100;

Since, 5 / 10 is already 0.. Casting the final result to any type will give you 0 only, as in below code: -

float percent = ((float)(score/numberOfQuestions))*100;

This will also give you 0.0. Since you are casting 0 to float. Doesn't matter..

Upvotes: 6

Related Questions