JavaScript eval() bug? 17:26 on Wednesday
This is a bit off of my regular content, but I’ve been playing with JavaScript for my Google Live Help proto. Any JavaScript gurus out there care to explain what’s going on here…
Here are a few eval() statements and the corresponding results from JavaScript:
eval("1.2+0.97") => 2.17
eval("1.2+0.98") => 2.1799999999999997
eval("1.2+0.99") => 2.19
eval("1.2+0.981") => 2.181
This can happen with other numbers as well, but certainly not with any combination. The calculation I noticed this with was:
eval("55+15+55+9.58+9.99+45.01+3.90+1.80+1.98") => 197.26000000000002
So much for reliable Web 2.0 spreadsheet apps then. ;)
Comments:
September 27th, 2006 at 18:37
It’s a decimal precision issue - I think you could use .toFixed with floats that are of same precision. With calculations that involve floats with varying precisions… ehh… you can always use your favourite search engine to find a rather simple (yet a bit inelegant) solution for that.
September 27th, 2006 at 18:46
If it’s about varying precisions, why doesn’t it go away if I use the same precision for all numbers (eg. 55.00)?
September 28th, 2006 at 0:05
It’s not a bug, it’s a consequence of using binary floating point numbers. For example, Appendix B of the Python Tutorial (http://docs.python.org/tut/node16.html) explains this well:
“Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. [...] Unfortunately, most decimal fractions cannot be represented exactly as binary fractions. A consequence is that, in general, the decimal floating-point numbers you enter are only approximated by the binary floating-point numbers actually stored in the machine”
September 28th, 2006 at 8:03
Binary fractions.. the magic word. Had to google it to really understand what those are about. Again, Dr. Math explains it well. Every day something new. :)