-1

Today while i am coding in Android, i find out a bug in Android and couldnt find possible way to handle it.

Question is

int PERT = Math.round(100 * (Total - StokAdet) / Total);

Everything is pretty good but when Total is 12 and StokAdet is 10, then something magicly happens and result brings me 16.

Normally the result is 16.6666667 but when rounded it must become 17. But it returns 16. I hope to hear you. Thanks..

HB.
  • 4,116
  • 4
  • 29
  • 53

3 Answers3

3

I'm guessing it's because you are doing an integer division here. So 100 * (Total - stokAdet) / Total is 16 already. Probably because Total and StokAdet are ints.

So if we evaluate it step by step as java would:

Total - StokAdet = 12 - 10 = 2

100 * (Total - StokAdet) = 100 * (12 - 10) = 200

100 * (Total - StokAdet) / Total = (100 * (12 - 10)) / 12 = 16

This last bit might seem odd because it should be 16.66666...7 by normal arithmetic right? Well because we are in Java and all of the numbers are integers the output will also be an integer. Integers can't represent the bit after the decimal point (the ".66666...7" bit). Now it might seem crude but what Java does is it just throws away the ".66666...7" bit so 16.66666...7 becomes just 16.

However if either the Total or StokAdet were float values then the calculation would give you your number as expected.

0

This is fine:

int PERT = Math.round(100 * (Total - StokAdet) / Total);

Just add this below

int i = Math.round(PERT);

Then i is the rounded number.

HB.
  • 4,116
  • 4
  • 29
  • 53
0

It's not a bug, it's a feature. H.Brooks answer shows how to get around it.

Why? You are are working in integers. And integers are not rounded up or down with division. They are cut off. In Java, int 1.9999999999999 is always going to be 1, not 2. So take a moment to pick the right variable for the right value.

Further reading: Division of integers in Java