Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division between integers in Java

I need to perform division between integers in Java, and the result should be a float.

Could I just use / symbol for it? As in:

int integer1 = 1;
int integer2 = 2;
float quotient = integer1 / integer2; // Could I do this?
like image 402
aneuryzm Avatar asked Mar 05 '11 09:03

aneuryzm


People also ask

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

How do you divide math in Java?

The Math. floorDiv() method divides one integer ( int or long ) by another, and rounds the result down to the nearest integer value. If the result is positive, the effect is the same as using the Java / division operator described earlier in this text.


1 Answers

Cast one of the integers to float to ensure a floating point division:

float result = integer1 / (float) integer2
like image 177
Adrian Cox Avatar answered Sep 22 '22 05:09

Adrian Cox