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

3 Answers

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

2

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy