2017-07-24 87 views
-1

我想顯示一個TextView用下面的代碼的百分比:無法在民調顯示正確的百分比值

int votedTotal_int = pollObject.getList("votedBy").size(); 
System.out.println("Total votes cast: " + Integer.toString(votedTotal_int)); 

int value1_int = pollObject.getList("value1Array").size(); 
double value1_pct = ((value1_int/votedTotal_int) * 100); 
String value1_string = String.valueOf(value1_pct); 
holder.value1.setText(value1_string + " %"); 
System.out.println(holder.value1.getText().toString() + " votes"); 

鑑於value1_int爲1,votedTotal_int是4,應該不是打印出閱讀25.0%?那麼,爲什麼我會得到以下?

07-24 16:48:21.626 13321-13321/com.test.android I/System.out: Total votes cast: 4 
07-24 16:48:21.626 13321-13321/com.test.android I/System.out: 0.0 % votes 
07-24 16:48:21.626 13321-13321/com.test.android I/System.out: 0.0 % votes 
07-24 16:48:21.626 13321-13321/com.test.android I/System.out: 0.0 % votes 
07-24 16:48:21.626 13321-13321/com.test.android I/System.out: 0.0 % votes 
+1

除兩個整數將使用整數除法(即3/4 == 0)。人們可以做'value1_int * 100.0/votedTotal_int'等。 –

+0

看到[Integer師](http://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0) –

回答

-1

更改下面..

double value1_pct = ((value1_int/votedTotal_int) * 100); 

double value = (((double)value1_int * 100)/((double)votedTotal_int)); 

樣品試驗與value1_int=1votedTotal_int=1000 or 10000 or 100000

07-24 17:09:13.904 3491-3491/? D/TEST: 0.1 
07-24 17:09:30.688 3589-3589/? D/TEST: 0.01 
07-24 17:09:45.366 3685-3685/? D/TEST: 0.001 
+0

嘗試你的代碼與這些值'int value1_int = 1; \t \t int votedTotal_int = 1000;' –

+0

這不應該是被接受的答案 - 這是錯誤的 –

+0

爲什麼?它工作得很好。 – santafebound

0
double value1_pct = (((double)value1_int * 100)/(double)votedTotal_int);