18

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?

Druckles
  • 3,161
  • 2
  • 41
  • 65
  • 4
    Note, though, (if you've been using python3.x) that in Java, dividing two integers will always use floor division. – HammerN'Songs Dec 19 '18 at 22:45
  • 4
    Java int division is not quite the same as Python's floor division. `//` rounds towards negative infinity. Java int division rounds towards zero. But `5 / 2` in Java will give you 2, if that is what you're after. – khelwood Dec 19 '18 at 22:47
  • 2
    You are looking for `Math.floorDiv()`. – Feuermurmel Oct 27 '19 at 14:34

4 Answers4

20

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

Jack Moody
  • 1,590
  • 3
  • 21
  • 38
A J
  • 1,439
  • 4
  • 25
  • 42
  • 1
    This isn't even correct. `Math.floor(a / b)` gives the same result as `a / b` when `a` and `b` have type `int`. In Python `5 // -2` gives `-3` where in Java `Math.floor(5 / -2)` gives `-2.0`. – Feuermurmel Oct 27 '19 at 14:27
9

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

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

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.

Gonzalinho
  • 29
  • 3
0

use floorDiv()

int x = 10;
int y = 3;
System.out.println(Math.floorDiv(x,y));
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 29 '23 at 08:26