This question has already been answered:

Why is the value of the counter itself incorrectly displayed and the accuracy at run time goes away?

public class DoubleFor { public static void main(String[] args) { for (double d = 0.1; d <= 1; d += 0.1 ){ System.out.println("d = " + d); } } 

}

compilation:

d = 0.1
d = 0.2
d = 0.300000000000004
d = 0.4
d = 0.5
d = 0.6
d = 0.7
d = 0.7999999999999999
d = 0.8999999999999999
d = 0.9999999999999999

Process finished with exit code 0

Reported as a duplicate at Nofate 4 May '16 at 11:56 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

3 answers 3

I borrow an explanation from Ilya Kantor. He talks about javascript, but all of this applies to most programming languages ​​without any changes:

The number 0.1 (one tenth) is written simply in decimal format. But in the binary number system it is an infinite fraction, since the unit of ten in the binary system is not so simple to divide. Also an infinite fraction is 0.2 (= 2/10).

The binary value of the infinite fractions is stored only up to a certain sign, so inaccuracy occurs.

When we add 0.1 and 0.2, then two inaccuracies add up, we get a minor, but still an error in the calculations.

https://learn.javascript.ru/number#netchnye- calculations

More information in English can be found at the link: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html#680

    The thing is that in the IEEE 754 standard exactly 8 bytes (= 64 bits) are allocated to the number, no more and no less.

    For example, the number 0.1 (one tenth) is written simply in decimal format. But in the binary number system it is an infinite fraction, since the unit of ten in the binary system is not so simple to divide. Also an infinite fraction is 0.2 (= 2/10).

    The binary value of the infinite fractions is stored only up to a certain sign, so inaccuracy occurs.

    When we add, for example, 0.1 and 0.2, then two inaccuracies are added, we get a minor, but still an error in the calculations.

    In this example, the same thing: the final value will never be equal to one.

    The same thing happens in any other language where IEEE 754 is used, including JavaScript, C, PHP, Ruby, Perl.

    Taken from the site by javascript

    • If you already copy word-for-word, it would be nice to indicate the source. - Alexey Ukolov
    • @ AlekseyUkolov, rightly so. Added by. hurried and forgot first) - I. Smirnov

    and the solution to the problem itself:

     public class DoubleFor { public static void main(String[] args) { for (double d = 0.1; d <= 1; d += 0.1 ){ System.out.println("d = " + Math.round(d*10)); } } }