Is there a form of the // operator that is used in python that I can use in java, or some sort of workaround? 10 // 3 = 3
5 Answers
In python 3 // act as a floor division by default.
In python 2.2 and later 2.X version we can import it from the __future__
>>> from __future__ import division
>>> 10/3
3.3333333333333335
>>> 10//3
3
In Java: When dividing floating-point variables or values, the fractional part of the answer is represented in the floating-point variable.
float f = 10.0f / 6.0f; // result is 1.6666
double d = 10.0 / 9.0; // result is 1.1111
But for floor in java:
(int)Math.floor(10/3);
Comments
One thing to notice is:
in python 3:
6 // -132 = -1
in java:
6 / -132 = 0
2 Comments
Java's integer division will act in the same way as the // operator in Python. This means that something like this:
(int) 9/4 == 2 is True
The cast here is even unnecessary because both 9 and 4 are integers. If one was a float or a double this cast would be necessary as java would no longer execute this statement as integer division. To be more explicit you could do this
(int)Math.floor(9 / 4);
which divides the numbers first and then floors the results to the nearest integer.