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?
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
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
You can easily use Math.floorDiv() method. For example:
int a = 15, b = 2;
System.out.println(Math.floorDiv(a, b));
// Expected output: 7
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.
use floorDiv()
int x = 10;
int y = 3;
System.out.println(Math.floorDiv(x,y));
//
rounds towards negative infinity. Java int division rounds towards zero. But5 / 2
in Java will give you 2, if that is what you're after.Math.floorDiv()
.