Integer Division (Why does 2 / 5 = 0?)

edited September 2017 in Common Questions

Taken from the Processing WIKI here: https://github.com/processing/processing/wiki/Troubleshooting

Why does 2 / 5 = 0 instead of 0.4?

The result of dividing two integers will always be another integer:

int a = 2;
int b = 5;
int result = a / b;
// result is zero

While somewhat confusing at first, this is later useful for more advanced programming.

To get fractions, use a 'float' instead:

float a = 2.0;
float b = 5.0;
float result = a / b;
// 'result' will be 0.4

It is not enough to just divide two integers and set them to a float:

float y = 2 / 5;

In this case, integer 2 is divided by 5, which is zero, and then zero is assigned to a float. The number doesn't become a float until the left hand side of the = sign. On the other hand, this:

float y = 2.0 / 5;

will work just fine. In this case, Java sees that 2.0 is a float, so it also converts the 5 to a float so that they can be divided, which makes it identical to:

float y = 2.0 / 5.0;

and because floats are being used on the right hand side, the result will be a float, even before it gets to the left hand side.

Tagged:
This discussion has been closed.