Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# floating point caculation problem

Stephen Suen
Ranch Hand
Posts: 34
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

Tom Blough
Ranch Hand
Posts: 263
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 ]

Steve Morrison
Greenhorn
Posts: 6
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 ]

Stephen Suen
Ranch Hand
Posts: 34
Thanks all.
Stephen

Zeeman Chen
Greenhorn
Posts: 9
Great! That problem is also confusing me!