0

I was having some problem when trying to perform calculation in Java. Here is my codes:

NumberFormat pctFormatter = NumberFormat.getNumberInstance();
    pctFormatter.setMinimumFractionDigits(0);
    pctFormatter.setMaximumFractionDigits(0);
    for(int count = 0; count< amtGenderList.size(); count++){
        if(amtGenderList.get(count).getGender().equals("M")){
            totalMale = Integer.parseInt(amtGenderList.get(count).getTotalAttendee())/totalAttendee * 100;
            Log.i("Male", String.valueOf(totalMale));
        }else{
            totalFemale = Integer.parseInt(amtGenderList.get(count).getTotalAttendee())/totalAttendee * 100;
        }
        Log.i("Total",amtGenderList.get(count).getTotalAttendee());
        Log.i("Gender",amtGenderList.get(count).getGender());
    }

    Log.i("M", pctFormatter.format(totalMale));
    Log.i("F", pctFormatter.format(totalFemale));

I printed out log to check the values. So bascially I have a totalAttendee variable to store the total attendee of certain event. Then from there, I execute another SQL to get the totalMale and totalFemale.

When I tried to perform some calculation to get the percentage of totalMale and female over totalAttendee, I am getting the results as:

12-01 17:20:26.348: I/Total(10393): 1
12-01 17:20:26.348: I/Gender(10393): F
12-01 17:20:26.348: I/Male(10393): 0.0
12-01 17:20:26.348: I/Total(10393): 2
12-01 17:20:26.348: I/Gender(10393): M
12-01 17:20:26.348: I/M(10393): 0
12-01 17:20:26.348: I/F(10393): 0

I managed to get the Total and Gender printed from Log so that means my retrieval has no problem. However, when I tried to convert it into percentage, I am getting 0. Any ideas?

1 Answer 1

2

You are doing integer division here:

Integer.parseInt(amtGenderList.get(count).getTotalAttendee())/totalAttendee * 100

If you do integer division, things get truncated, so for example 75 / 100 is 0.

Do floating-point division instead, by converting one of the values to for example a double:

Integer.parseInt(amtGenderList.get(count).getTotalAttendee()) / (double) totalAttendee * 100
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.