Why does 0.1 + 0.2 evaluate to 0.30000000004? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why does 0.1 + 0.2 evaluate to 0.30000000004?

I think I put too many 0's there. Sorry for that. But why does it happen?

15th Oct 2016, 12:40 PM
Mashfiqun Nabi
Mashfiqun Nabi - avatar
4 Answers
+ 4
Such things may happen when manipulating numbers that aren't a sum of powers of two (and I'm including 0.5, 0.25, 0.125, etc.), due to how numbers are stored in memory. Especially when manipulating floats instead of doubles. http://www.binaryconvert.com/result_float.html?decimal=048046049 http://www.binaryconvert.com/result_float.html?decimal=048046050 See the "most accurate representation" those conversions give? That's an approximation of the value they take in memory when you convert them back to base 10. The problem still exists with doubles, but to a much lesser degree, as they use twice the memory space compared to floats, allowing for a much higher precision.
15th Oct 2016, 1:23 PM
Zen
Zen - avatar
+ 4
To explain the problem a bit better: You know how the fraction 1/3 is 0.3333333... in base 10? In base 3, it would simply be written 0.1. Here, it's kinda the same situation, we have an infinitely repeating sequence in base 2 (0.00011001100110011...) that is simply written 0.1 in base 10. Hence the inevitable approximation when converting 0.1 to binary to store it in memory.
17th Oct 2016, 9:32 AM
Zen
Zen - avatar
+ 2
Btw, while upvotes don't really matter for questions, make sure to upvote the best answers, so they appear first.
17th Oct 2016, 9:41 AM
Zen
Zen - avatar
+ 1
Well, Zen gets an upvote even if they don't matter. I know how some datatypes are stored internally but that's the first time I've seen that site; thanks.
17th Oct 2016, 4:08 AM
Kirk Schafer
Kirk Schafer - avatar