1

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
Ghoztrider
  • 145
  • 1
  • 11
  • 1
    Possible duplicate of [Int division: Why is the result of 1/3 == 0?](https://stackoverflow.com/questions/4685450/int-division-why-is-the-result-of-1-3-0) – Carcigenicate Oct 13 '19 at 19:37
  • 1
    Also, what's `* 1.00` for? That won't effect anything. Did you mean `* 100`? – Carcigenicate Oct 13 '19 at 19:37
  • The modulus operator computes the remainder from dividing a number by another https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic&ved=2ahUKEwic4PevhZrlAhXITN8KHS4BBDQQFjAhegQIChAB&usg=AOvVaw35MZ6AGPnm_JKfHB8hC79o – Felipe Gutierrez Oct 13 '19 at 20:10

2 Answers2

5

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).
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1
  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;
  }
Amit Sargar
  • 271
  • 2
  • 5