Java - How to do floor division?

62.9k Views Asked by At

I know that in Python you can do floor division like this:

5 // 2 #2

The // is used for something totally different in Java. Is there any way to do floor division in Java?

4

There are 4 best solutions below

2
On BEST ANSWER

You can do

double val = 5 / 2;
int answer = Math.floor(val);

OR

int answer = Math.floorDiv(5, 2);

If you were to call System.out.println(answer); the output would be

2

0
On

If you're using integers in the division and you cast the solution to another integer (by storing the result in another integer variable), the division is already a floor division:

int a = 5;
int b = 2;
int c = 5/2;
System.out.println(c);
>> 2

As khelwood stated, it also works with negative values but the rounding is done towards 0. For example, -1.7 would be rounded to -1.

1
On

use floorDiv()

int x = 10;
int y = 3;
System.out.println(Math.floorDiv(x,y));
0
On

You can easily use Math.floorDiv() method. For example:

int a = 15, b = 2; 
System.out.println(Math.floorDiv(a, b));
// Expected output: 7