// Why does 0.888888889 round down to 88 instead of up to 89? I need the output in int format.
int[] percentage = new int[4];
percentage[0] = 100 * countB[0] / (10 - countDash[0]);
percentage[1] = 100 * countB[1] / (20 - countDash[1]);
percentage[2] = 100 * countB[2] / (20 - countDash[2]);
percentage[3] = 100 * countB[3] / (20 - countDash[3]);
for (int i = 0; i < countB.length; i++) {
double d = percentage[i];
percentage[i] = (int) Math.round(d);
}
System.out.println(Arrays.toString(percentage));

- 40,516
- 21
- 95
- 125

- 73
- 7
-
2Integer division in Java does not round, it truncates. – President James K. Polk Aug 05 '18 at 00:01
1 Answers
To set this all out for you, the problem arises here:
int[] percentage = new int[4];
percentage[0] = 100 * countB[0] / (10 - countDash[0]);
Assuming that the code compiles, we can deduce that all of the variables have type int[]
.
That means that the expression will be evaluated using 32 bit integer arithmetic.
That means that the division is an integer division.
But in Java, integer division "rounds towards zero". In other words, it truncates the result. (Reference JLS 15.7.2)
So 800 / 9 -> 88.88888889 -> 88 NOT 89.
Later on you do this:
percentage[i] = (int) Math.round(d);
Unfortunately, you did that too late. The "damage" was done when you did the original (integer) division.
One solution: use floating point arithmetic and then do the rounding up:
percentage[0] = (int) Math.round(100.0 * countB[0] / (10 - countDash[0]));
Note that we changed 100
to 100.0
so that the expression will be evaluated using floating point rather than integer arithmetic.
You can then get rid of the loop that tried to round the percentages.

- 698,415
- 94
- 811
- 1,216