Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Rounding percentages

807601Dec 20 2007 — edited Dec 20 2007
            everybodycount = collcount + gradcount + faccount + staffcount;
            percentage = ((double)collcount / (double)everybodycount)*100;
            decf = new DecimalFormat("#0");
            collpct = Integer.parseInt(decf.format(Math.round(percentage)));
            System.out.print("College students = " + collcount + "," + collpct + "% of total population\n");
            percentage = ((double)gradcount / (double)everybodycount)*100;
            decf = new DecimalFormat("#0");
            gradpct = Integer.parseInt(decf.format(Math.round(percentage)));
            System.out.print("Grad students = " + gradcount + "," + gradpct + "% of total population\n");
            percentage = ((double)faccount / (double)everybodycount)*100;
            decf = new DecimalFormat("#0");
            facpct = Integer.parseInt(decf.format(Math.round(percentage)));
            System.out.print("Faculty (minus emeriti - only tenured faculty and senior lecturers included) = " + faccount + "," + facpct + "% of total population\n");
            percentage = ((double)staffcount / (double)everybodycount)*100;
            decf = new DecimalFormat("#0");
            staffpct = Integer.parseInt(decf.format(Math.round(percentage)));
            System.out.print(collpct + gradpct + facpct + staffpct + "= 100% of total population\n");
The above code calculates what percentage of a total population is a given subpopulation. They should add up to 100% - but the number (collpct + gradpct + facpct + staffpct) always comes out to 101 or 102. I suspect I am not rounding them the right way. How can I fix so that they add up to 100 percent? Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 17 2008
Added on Dec 20 2007
5 comments
283 views