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?

3
  • 4
    Note, though, (if you've been using python3.x) that in Java, dividing two integers will always use floor division. Dec 19, 2018 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, 2018 at 22:47
  • 2
    You are looking for Math.floorDiv(). Oct 27, 2019 at 14:34

4 Answers 4

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

1
  • 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. Oct 27, 2019 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.

0

use floorDiv()

int x = 10;
int y = 3;
System.out.println(Math.floorDiv(x,y));
1
  • 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.
    – Community Bot
    Jan 29 at 8:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.