This week's book giveaways are in the Java EE and JavaScript forums. We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line! See this thread and this one for details.

Hi all, I'm stucked. Here's a very simple class: public class Multi{ public static void main(String args[]){ System.out.println("3.0 * 0.2 = " + (3.0 * 0.2)); } } The output is as follow: 3.0 * 0.2 = 0.6000000000000001 Why the result is wrong? Any help will be appreciated. Stephen

The result is not wrong. Computers use binary numbers which don't always EXACTLY represent decimal numbers. Using decimal numbers, we cannot exactly represent 1/3. The decimal equivalent is 1.333333333 where the 3 repeats forever. The same thing happens with binary numbers. We can accurately represent 1/2 decimal as 0.1 binary. However, 0.2 decimal is represented as 0.0011001100110011 where the 0011 repeats forever. When you cannot accurately represent the number in binary, small errors creep in when doing mathematical operations. What you are seeing is the result of those errors. In science and engineering courses, you learn about a thing called "Significant Figures". Basically this says that your first number "3.0" has two significant digits. Your dividend "0.2" has one significant digit. Therefore, your result will only have one significant digit so the only portion of the result that is correct is the "0.6". There rest should be ignored. Hope this helps. [ October 30, 2003: Message edited by: Tom Blough ] [ October 30, 2003: Message edited by: Tom Blough ]

Tom Blough<br /> <blockquote><font size="1" face="Verdana, Arial">quote:</font><hr>Cum catapultae proscriptae erunt tum soli proscripti catapultas habebunt.<hr></blockquote>

If you want to cut down your answer to a certain number of places you can use DecimalFormat...for example import java.text.*; public class Multi{ public static void main(String args[]){ DecimalFormat df = new DecimalFormat("0.0"); System.out.println("3.0 * 0.2 = " + df.format(3.0 * 0.2)); } } ...you can change the numbers in the quotes to give you the desired number of decimal places. Of course, I'm new at this so there might be an easier method to format your output. [ October 30, 2003: Message edited by: Spiff Wilkie ]