Why 0.1+0.2 is not 0.3 in javascript ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why 0.1+0.2 is not 0.3 in javascript ?

Why 0.1+0.2 is not 0.3 in javascript ?

17th Jan 2017, 2:36 AM
Vikas Yadav
Vikas Yadav - avatar
3 Answers
+ 4
Floating point rounding errors. 0.1 cannot be represented as accurately in base-2 as in base-10 due to the missing prime factor of 5. Just as 1/3 takes an infinite number of digits to represent in decimal, but is "0.1" in base-3, 0.1 takes an infinite number of digits in base-2 where it does not in base-10. And computers don't have an infinite amount of memory.
17th Jan 2017, 3:41 AM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 3
Yeah, to get 0.3 you actually have to do (0.1 * 10 + 0.2 * 10) / 10
17th Jan 2017, 2:40 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 1
It's caused by the way of numbers are stored internaly by JS. Detailled explications there: http://www.w3schools.com/js/js_numbers.asp
17th Jan 2017, 3:39 AM
visph
visph - avatar