Ghoztrider
Ghoztrider

Reputation: 145

Method involving math giving different answer than calculator

I'm new to java so please bear with me. I'm trying to get the percentage of wins from total number of games and something I'm doing is way off. My method for getting the percentage is below:

public double winPercentage(int wins, int total)
{
    return (wins % total) * 1.00;
}

If I win 52 games out of 254 my answer comes up to 52.0, using my calculator that same answer is 20.47 assuming wins/total*100. If I switch the modulus to / I constantly get 0.0

I've tried a variation of different decimal places and order of operations. I can't seem to get the calculator and method to match up.

Upvotes: 1

Views: 191

Answers (2)

Amit Sargar
Amit Sargar

Reputation: 281

  1. Java uses % as modulo operator, so it will always return the remainder as a result not percentage.
  2. If we divide integer by integer, then result will not be precise as required for percentage function. E.g. if we try to divide 52 by 254 result will be 0 for an integer not 0.2047, as integer is capable of holding complete numbers only. So to get percentage, you can use double/float as parameter data type like below instead of integer. 
public double winPercentage(double wins, double total) {
     return wins / total * 100;
  }

Upvotes: 1

NPE
NPE

Reputation: 500377

The percent sign in wins % total has no relationship to computing a percentage.

To compute percentage in Java, you could write

return 100.0 * wins / total;

Here, 100.0 serves dual purpose:

  • it rescales the result to percentage points;
  • it turns the subsequent division into a floating-point one (without which it's an integer division, always returning zero when wins < total).

Upvotes: 5

Related Questions