confused with double operations
1 posts in topic
Flat View  Flat View

Posted By:   Alexey_Yastremskiy
Posted On:   Tuesday, April 5, 2005 02:11 AM

Hello everybody.

Consider the following class code:

public class test {

public static void main( String s[]) {

double a = 129.7;
double b = 18;
double c = a - b;

System.out.println( a + " - " + b + " = " + c );

the result will be 111.69999999999999? while expecting just 111.7. If I change a=29.7, then I will get 11.7 as expected. So, the result depends on the operands.
Could you please explain this...

Re: confused with double operations

Posted By:   Anonymous  
Posted On:   Friday, April 8, 2005 01:26 AM

You probably heard that your computer uses binary numbers. With binary numbers, many decimal numbers cannot be represented exactly. So the internal binary representation is a little bit off, and the internal sum is a little bit more off. When the output string (the decimal number) is computed, there is again a little error. Sometimes you are lucky, and the errors cancel each other; sometimes they don't.


(a) When using double, always assume that the numbers will come out a little wrong!!! If this is not acceptable, you MUST USE BigDecimal (in package java.math)!!!!!

(b) If you want to know what really goes on, read any introduction to computer numerics (and prepared for quite some math). After you have understood all in there, you will know whan you can use doubles safely and when not.


Harald M.

About | Sitemap | Contact