Evan Darwin - 7 months ago 17

Java Question

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);

progdialog.setProgress(percentage);

Percentage always equals percentage.

Why?

Answer

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.