I have a problem with adding double to double. The program sometimes adds like 0,2000000004 to the counter instead of 0,2. Why is that so?

This site requires JavaScript, please enable it in your browser!

Turbo_Thorsten wrote...

I have a problem with adding double to double. The program sometimes adds like 0,2000000004 to the counter instead of 0,2. Why is that so?In the computer, numbers are stored in binary (only 0s and 1s as ciphers) instead of decimal (0, 1, 2, ...9).
That means, for floating point numbers, the fraction ciphers, will be powers of (1/2):
0.1 (binary) is 1/2
0.01 (binary) is 1/4
0.001 (binary) is 1/8 and so on...
Now, it can only add up these ciphers to represent numbers, so, e.g. 3/4 can be easily stored in binary since it is 1/2 + 1/4, so it's binary representation is 0.11 (binary) = 0.75 (decimal).
But the binary representation of 0.2 (decimal) is very difficult because it can not be represented by a finite number of 1/2^n fractions. But a double only has a finite number of bits (It is 64 bits in Java), therefore the value saved in the double will only be an approximation of 0.2 (decimal) and not actually exactly 0.2, e.g. the stored value will be more like 0.200000000000000011102230246251565404236316680908203125...
In most cases, the difference between the actual value and the stored value will not be visible. But when modifying the value (e.g. with addition and especially multiplication), the difference can get bigger and then become visible like in your case.
So, whether the accuracy of Double is good enough, depends strongly on what operations one is doing with the numbers. Also, doing operations in the "right" order can help with keeping the difference small.
In Java, there is a type called BigDecimal that can be used, if bigger or absolute precision/accuracy is needed (e.g. for any financial values):
https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
Edit: Danpost was faster than me. :)
Live long and prosper,
Spock47

Thank yall for the answers. I got an easy solution but the explanation is very helpful :)

You need to login to post a reply.