2

Possible Duplicate:
Retain precision with Doubles in java

import static java.lang.System.out;
public class q2{  
    public static void main(String args[]){  
        double x=4.02, y=0.05;  
        out.println(x+y);  
    }  
}

Output:

4.069999999999999

Why is it outputting the that. I thought it would be 4.07. Please explain why this happens in java ?

Sorry for the inaccurate Question title. I can't have a better title than this

Community
  • 1
  • 1
Vishnu Pradeep
  • 2,087
  • 2
  • 29
  • 56
  • 1
    Why? It's the correct answer, considering the real values of x and y. – Jacob Aug 01 '11 at 17:36
  • The question is, in any future calculation will 4.07 be any different to 4.06999999999999. If you want your final answer to some specific precision then just round at the end. – James Gaunt Aug 01 '11 at 17:41
  • 2
    The discovery of floating point arithmetic marks an important milestone in every programmer's life. Congratulations. :) – Adam Paynter Aug 01 '11 at 17:41

2 Answers2

3

That is because some numbers -- such as 0.1 -- cannot be represented exactly in binary floating-point.

Consider reading the following article:

João Silva
  • 89,303
  • 29
  • 152
  • 158
1

You are seeing a rounding error. See How to resolve a Java Rounding Double issue

To resolve it you can change to BigDecimal instead of double as mentioned in the accepted answer to the linked question.

Community
  • 1
  • 1
digitaljoel
  • 26,265
  • 15
  • 89
  • 115