2

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

1
  • 3
    10 / 3 will have the same behavior. Java performs integer division if both operand are int (or long) Commented Nov 30, 2014 at 19:45

5 Answers 5

5

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);
Sign up to request clarification or add additional context in comments.

Comments

3

One thing to notice is:

in python 3:

6 // -132 = -1

in java:

6 / -132 = 0

2 Comments

For interger division in python, we need: math.trunc(a / float(b))
Very surprising that very few seem to be aware of this - Python integer division (old or new) was never like C/Java integer division, unless there are only non-negative integers in your universe.
1
public static int python_like_divisor(int x, int y) {
    final remainder = x % y;
    if(remainder != 0) {
        return (x - remainder) / y;
    }
    return x / y;
}

Some basic math knowledge is good ;)

With float-point (float, double etc.) values this method will not work properly.

Comments

0

You can use java.lang.Math#floorDiv(int, int)

Comments

-1

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.

Comments

Your Answer

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