Get Percent From Two Numbers Using Java

Here is a simple method for getting the percent of a subtotal from the total. If you noticed in the code, I had to cast both the subtotal and total variables to float before casting the final result to an int.

This is because if you divide two numbers and both are of type int, the result will also be an int. Casting both variables to float before dividing them did the trick.

public static int getPercentFromTotal(int subtotal, int total) {
    return (int) (((float) subtotal / (float) total) * 100);
}

Donations appreciated. Every little $ helps. Or click Google +1. Or play the short video on the upper right of this page.

Related Posts Plugin for WordPress, Blogger...