Let's set aside the potentially greater issue of your using a binary floating point for a quantity that requires a precise decimal representation.
The Java bods broke with tradition and decided that Math.round(interest * 100)
should return a long
, rather than a double
. (I imagine they did this since any double
that is not an integer will be rounded to an integer that can fit into a long
type). So the expression
Math.round(interest * 100) / 100
is evaluated in integer arithmetic, so any remainder is discarded. The clearest workaround in my opinion is to write
interest = Math.round(interest * 100) / 100.0;
which forces evaluation to take place in floating point.
Also note that the resultant underlying floating point value will, in general, have trailing non-zero digits past the 2nd decimal place even after this rounding has been applied: a double
only gives you 15 decimal significant figures of precision.