Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Why does adding 0.1 to 0.2 return 0.30000000000000004???

843789Mar 6 2010 — edited Mar 6 2010
I am writing a program for class project and I am incrementing a variable of type double by 0.1 in a loop. My expected result should look something like 0.1, 0.2, 0.3.....100.1, 100.2... and so on................. but instead this is what I am getting --

0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
1.2
1.3
1.4000000000000001
1.5000000000000002
1.6000000000000003
1.7000000000000004
1.8000000000000005
1.9000000000000006
2.0000000000000004


Why is the result so odd?? Furthermore, if I change the variable type to float, the result is similar, but different

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001
1.0000001

Why is it happening and what can be a good solution to the issue??
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 3 2010
Added on Mar 6 2010
8 comments
747 views