Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I divide without flooring in Java?

Tags:

java

integer

I'm trying to divide an integer by an integer in Java and return a long result. I tried the following, but I keep getting "0".

System.out.println(Long.valueOf(5) / Long.valueOf(18));
System.out.println((long)5 / (long)18);
like image 209
Leo Jiang Avatar asked Jan 03 '12 00:01

Leo Jiang


3 Answers

You don't need a long, you need a double.

System.out.println(5 / 18.0);

or

System.out.println(5.0 / 18);

Of course this will work too:

System.out.println(5.0 / 18.0);
like image 200
Sergey Kalinichenko Avatar answered Nov 13 '22 10:11

Sergey Kalinichenko


It seems everyone has given the right answer, but you should note you can also do

System.out.println(5 / 18f)

Where f makes it a float

System.out.println(5 / 18d)

where d makes it a double

like image 6
AlanFoster Avatar answered Nov 13 '22 11:11

AlanFoster


Long is for "long" integer numbers. You should use float or double instead.

like image 5
Aurelio De Rosa Avatar answered Nov 13 '22 09:11

Aurelio De Rosa