Take the 2-minute tour ×

This is a ridiculous question but I can't find an answer. Have 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).

share|improve this question
Did you try (double)completed / (double) total ... and then assigning result to a double? –  Sagar V Aug 28 '11 at 11:36
try completed * 1.0 /total –  user12384512 Aug 28 '11 at 11:38

4 Answers 4

up vote 24 down vote accepted

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


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

share|improve this answer
facepalm That did it, thanks. Saved me about...one month off my baldness schedule. –  Steve Aug 28 '11 at 11:37
You don't need to cast them both, one is enough. –  Jack Aug 28 '11 at 11:37
@Jack: I've just updated my answer to address this. –  Oliver Charlesworth Aug 28 '11 at 11:38

You don't even need doubles for this. Just multiply by 100 first and then divide. Otherwise the result would be less than 1 and get rounded to zero, as you saw.

edit: or if overflow is likely, if it would overflow (ie the dividend is bigger than 922337203685477581), divide the divisor by 100 first.

share|improve this answer

Convert both completed and total to double or at least cast them to double when doing the devision. I.e. cast the varaibles to double not just the result.

Fair warning, there is a floating point precision problem when working with float and double.

share|improve this answer

If you don't explicitly cast one of the two values to a float before doing the division then an integer division will be used (so that's why you get 0). You just need one of the two operands to be a floating point value, so that the normal division is used (and other integer value is automatically turned into a float).

Just try with

float completed = 50000.0f;

and it will be fine.

share|improve this answer

Your Answer


