简体   繁体   中英

Java Formatting Float Decimal Points

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?

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

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