Eighty percent done, shown as zero
A easy Java puzzle in the numeric overflow and precision family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 3. Play this one as a puzzle without the answer.
What is wrong
done / total is integer division, which truncates 0.8 to 0 before the multiplication happens. Every value except a completed task shows 0 percent. Order of operations decides when the fraction is lost.
The fix
How to avoid it next time
Multiply before dividing when working with integers, or convert to double (done * 100.0 / total) and round explicitly.
Want the background? Read Primitive types and floating point in the Java concepts library.
About numeric overflow and precision
Java integers wrap around silently when they exceed their range, with no exception. int and long arithmetic, integer division and implicit narrowing casts all produce wrong numbers that look plausible.
In code review: Look at the type of every operand, not the type of the variable receiving the result. Multiplication of two ints happens in int even when assigned to a long. Use Math.addExact, long literals and BigDecimal for money.
More puzzles in this family
Frequently asked questions
What is the bug in "Eighty percent done, shown as zero"?
done / total is integer division, which truncates 0.8 to 0 before the multiplication happens. Every value except a completed task shows 0 percent. Order of operations decides when the fraction is lost. The faulty line is line 3: return done / total * 100;
How do I fix it?
Replace it with: return done * 100 / total;. Multiply before dividing when working with integers, or convert to double (done * 100.0 / total) and round explicitly.
How do I catch numeric overflow and precision in code review?
Look at the type of every operand, not the type of the variable receiving the result. Multiplication of two ints happens in int even when assigned to a long. Use Math.addExact, long literals and BigDecimal for money.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.