0
public static void main(String[] args) {
    double test = 1;
    int tick = 0;
    while(tick < 10){
        System.out.println(test += 1.4);
        tick++;
    }
}

Result:

2.4
3.8
5.199999999999999
6.6
8.0
9.4
10.8
12.200000000000001
13.600000000000001
15.000000000000002

I don't understand why It get these strange decimal numbers like 5.19 instead of 5.2 Why is this? And is there a way to just make it appear to 5.2 like my calculator does? Thanks in advance. Marten

user1621988
  • 4,215
  • 8
  • 27
  • 31
  • This is a very common question and some minimal research would reveal the answer. In short you need to round your result, either in calculation or when you print it. – Peter Lawrey Aug 01 '13 at 10:15
  • 2
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – AllTooSir Aug 01 '13 at 10:15
  • @assylias Please don't point to duplicates, look for the original question (I think http://stackoverflow.com/questions/5257166/java-floats-and-doubles-how-to-avoid-that-0-0-0-1-0-1-0-9000001 is the root of the duplication tree, it hasn't been closed). – Maarten Bodewes Aug 01 '13 at 10:18

1 Answers1

1

It's just the way double is working. It ain't perfect. What you see is rounding errors, caused by the fact that not all numbers can be accurately represented in binary.

If you want to go for precision, you should try BigDecimal instead.

MightyPork
  • 18,270
  • 10
  • 79
  • 133