First of all, I like your question title. “Double trouble”. Very creative
Anyways, to answer your question, floating-point arithmetic is almost never exact in any programming language. Read this article to find out more information: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
One way Java programmers solve this is by using the BigDecimal class. Here’s the javadoc for that
Briefly, to multiply two BigDecimals, you would do:
BigDecimal d1 = new BigDecimal( "0.22132" ); // I chose 0.22132 arbitrarily.
BigDecimal d2 = new BigDecimal( "0.123" ); // I chose 0.123 arbitrarily too.
System.out.println( d1.multiply(d2) );
The output would be 0.02722236 (I checked with my calculator. This is the correct answer).
Now, if you did this with doubles like this,
System.out.println( 0.22132 * 0.123 );
You’d get 0.027222359999999998
One other way of solving this sort of problem (it won’t work here though) is to just cast the double as you’re printing it out. So, your output statements would be
System.out.println( (int)(a) );
It won’t work here though since casting just truncates the decimal values. So, if you did casting, all your outputs would be 0. However, if this problem shows up again, casting might be a solution.
But, for this particular problem, BigDecimal is your way to go.