Search code examples
javamathfloating-pointlong-integerprintln

Division of integers in Java


This is a basic question but I can't find an answer. I've looked into floating point arithmetic and a few other topics but nothing has seemed to address this. I'm sure I just have the wrong terminology.

Basically, I want to take two quantities - completed, and total - and divide them to come up with a percentage (of how much has been completed). The quantities are longs. Here's the setup:

long completed = 25000;
long total = 50000;

System.out.println(completed/total);  // Prints 0

I've tried reassigning the result to a double - it prints 0.0. Where am I going wrong?

Incidentally, the next step is to multiply this result by 100, which I assume should be easy once this small hurdle is stepped over.

BTW not homework here just plain old numskull-ness (and maybe too much coding today).


Solution

  • Converting the output is too late; the calculation has already taken place in integer arithmetic. You need to convert the inputs to double:

    System.out.println((double)completed/(double)total);
    

    Note that you don't actually need to convert both of the inputs. So long as one of them is double, the other will be implicitly converted. But I prefer to do both, for symmetry.