int a = (int) ((0.7 + 0.1) * 10). Why a = 7?

java

Solution

The issue is that neither 0.1 nor 0.7 can be represented exactly as `double`:

`0.1` gets represented as approximately `0.10000000000000000555`.

`0.7` gets represented as approximately `0.69999999999999995559`.

Their sum is approximately `0.79999999999999993339`. Multiplied by ten and truncated, this gives `7`.

What Every Computer Scientist Should Know About Floating-Point Arithmetic is an excellent read on the subject.

Problem

I have question to everybody. ``` int a = (int) ((0.7 + 0.1) * 10) ``` After executing of this code, a = 7. I can`t understand why, because (0.7+0.1)=0.8 and 0.8*10=8. Can anybody tell me why? Thanks!

Original source

Related problems