简体   繁体   中英

Basic java calculation issue

 Cursor ca2 = dbh1.getReadableDatabase().query(DatabaseHelper.TABLE_NAME, null, null,     null, null, null, null);
 int countTotal = ca2.getCount();
 Cursor ca1 = dbh1.getReadableDatabase().query(DatabaseHelper.TABLE_NAME, null, DatabaseHelper.VALUE6 + "='Automatic'", null, null, null, null);
 int count = ca1.getCount();

 int percentTrans = ((count/countTotal)*100);
 statText=(EditText)findViewById(R.id.etext3);
 statText.setText(Integer.toString(percentTrans));

 Toast toast=Toast.makeText(this, Integer.toString(percentTrans), 2000);
 toast.show();

Hello, i have a silly problem here. I want to the percentage by dividing count over countTotal and multiplying that by 100. percentTrans is integer by nature and this value will be passed to an edit text which requires that percentTrans be converted to string. count is 2 and countTotal is 3. But i get 0 as the result. Any ideas?

count/countTotal is int too and (int)(2/3) is 0 .

write it as (count*100/countTotal)

Integer math is not like using a calculator - do this instead:

int percentTrans = Math.round(count * 100.0f / countTotal);

this does all of the calculations as floating point numbers (it does this implicitly when you specify your 100.0f to be a float) and then rounds it to the appropriate integer value at the end

jus do calculation as upper shown answer and put value in edit text as followin:

statText.setText(String.valueOf(percentTrans));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM