This week's book giveaway is in the Servlets forum. We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line! See this thread 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 ]