Basic java calculation issue

Go To StackoverFlow.com

0

 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?

2012-04-04 17:36
by Nidhin_toms


4

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

write it as (count*100/countTotal)

2012-04-04 17:39
by kirilloid


1

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

2012-04-04 17:44
by JRaymond
Math.round would be even better - kirilloid 2012-04-04 17:50


1

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

statText.setText(String.valueOf(percentTrans));
2012-04-04 17:48
by Chintan Raghwani
Ads