0

I'm working on something that requires some very simple arithmetic, but some of the results that come up are just mind-boggling.

For example, paste the following in Chrome / Firefox / Opera DevTools console:

(211.8 - 0.5) + 0.8

The result should be 212.1.... but I keep getting 212.10000000000002

Although I can work around it using toFixed() or Math.ceil() etc. I would like to know what causes things like that to happen.

I may have passed it off as a JSVM bug on a particular JS runtime, but it happens on multiple JS engines.

Any JS / JSVM gurus care to enlighten me?

ekhaled
  • 2,930
  • 20
  • 24
  • This can be simplified to 211.3 + 0.8 and still returns the same result. –  Aug 15 '13 at 12:03
  • 1
    Also these: http://stackoverflow.com/questions/tagged/floating-point?sort=frequent – Kobi Aug 15 '13 at 12:04
  • Why does it happen on this particular number, and if it's about binary precision.. wouldn't it affect IE js engine the same way? – ekhaled Aug 15 '13 at 12:10
  • 1
    Not if IE's engine is implemented differently (obviously). That said, nothing points to it being implemented differently. It's just that the *console* behaves differently. Notice e.g. that `212.10000000000002` => `212.1`, but `212.10000000000002.toString()` => `212.10000000000002` and `212.10000000000002 == 212.1` => `false` (i.e. it's not that the two numbers have the same internal floating point representation). In other words, the console appears to simply try to make the output more "reader friendly" by rounding the output. The actual JS engine behaves the same as the other browsers. – JimmiTh Aug 15 '13 at 12:47

0 Answers0