Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division of integers in Java [duplicate]

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).

like image 206
Ben Avatar asked Aug 28 '11 11:08

Ben


People also ask

Can you divide an int by a double in Java?

PROGRAM 2 In Java, when you do a division between an integer and a double, the result is a double.

What happens when you divide two integers in Java?

When dividing two integers, Java uses integer division. In integer division, the result is also an integer. The result is truncated (the fractional part is thrown away) and not rounded to the closest integer.


2 Answers

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.

like image 132
Oliver Charlesworth Avatar answered Oct 18 '22 13:10

Oliver Charlesworth


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 truncated 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.

like image 32
harold Avatar answered Oct 18 '22 14:10

harold