I am trying to do some simple percents, and My results always is zero.
String taste = jsonArray.getJSONObject(i).getString("taste");
String rate = jsonArray.getJSONObject(i).getString("rate");
Log.d("taste", rate);
int rateNum = Integer.parseInt(rate);
Log.d("taste", "rateNum is " + rateNum);
int percent = rateNum / count;
percent = percent * 100;
Log.d("taste", "percent is " + percent);
The odd part is looking at my Log my rateNum and count Variables are both numbers and not zero:
06-26 21:52:44.319: D/taste(11812): count it:20
06-26 21:52:44.319: D/taste(11812): 13
06-26 21:52:44.319: D/taste(11812): rateNum is 13
06-26 21:52:44.319: D/taste(11812): percent is 0
06-26 21:52:44.319: D/taste(11812): 3
06-26 21:52:44.319: D/taste(11812): rateNum is 3
06-26 21:52:44.319: D/taste(11812): percent is 0
06-26 21:52:44.319: D/taste(11812): 3
06-26 21:52:44.319: D/taste(11812): rateNum is 3
06-26 21:52:44.319: D/taste(11812): percent is 0
06-26 21:52:44.319: D/taste(11812): 1
06-26 21:52:44.319: D/taste(11812): rateNum is 1
06-26 21:52:44.319: D/taste(11812): percent is 0
So I have no idea why I keep getting zero as my percent.
You are suffering from mistakes with numerical type.
When you get rateNum, it is an int
, as is count. Since int/int=int(truncating decimals), you are multiplying 0 by 100 to get 0.
The solution is as follows:
String taste = jsonArray.getJSONObject(i).getString("taste");
String rate = jsonArray.getJSONObject(i).getString("rate");
Log.d("taste", rate);
double rateNum = Double.parseInt(rate);
Log.d("taste", "rateNum is " + rateNum);
double percent = rateNum / count;
percent = percent * 100;
Log.d("taste", "percent is " + percent);
You might want to try
int percent = (100*rateNum) / count;
or use floating point for the math. Your value is being rounded down to zero and then never recovering.
You are using int type to save the percent, so a number like 0.8 will be rounded to 0 at int percent = rateNum / count;
Use this instead
float percent = rateNum / count;
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.