Evan Darwin Evan Darwin - 1 year ago 39
Java Question

Java divison with two integer operands not working?

For some reason my math just returns 0. The value are set, I have checked.

int currentSize = 4079;
int totalSize = 500802;

int percentage = ((currentSize/totalSize) * 100);

Percentage always equals percentage.


The problem, as other have pointed out, is integer division will turn anything less than 1 to zero. This happens before multiplying by 100. You can change the order of operations to get something better:

int percentage = currentSize * 100 / totalSize;

If you are concerned about rounding, you can use

int percentage = (currentSize * 100 + (totalSize >> 1)) / totalSize;

These avoid the expense of working with double or float values.