Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Java percentage calculation

I can't figure out what's wrong with this code... I'm trying to calculate a percentage:

I'm sure that boath npage and numpages are greater than zero (checked it on the emulator's debug variables inspector), but the resulting cCom is always 0:

Double cCom=(double)(npage/numpages);

tpercent.setText("("+cCom.toString()+"%)");

Any ideas?

like image 913
pmc Avatar asked May 09 '11 22:05

pmc


1 Answers

If npage and numpages are both integers, then Java will round (npage/numpages) to an integer (i.e. 0). To make Java do the division with doubles, you need to cast one of the numbers to a double, like this:

Double cCom = ((double)npage/numpages);

In fact, because you're working with a percentage, you probably want:

Double cCom = ((double)npage/numpages) * 100;
like image 154
thomson_matt Avatar answered Sep 21 '22 11:09

thomson_matt