ofkpew
Last Updated: February 25, 2016
·
176
· szymonkor
Zrzut ekranu z 2016 04 16 07 43 55

Floating point numbers in JS

I believe I could have titled the post "0.1+0.2=0.30000000000000004" because inner jokes get more clicks!

I read an interesting article on floating point numbers (http://blog.chewxy.com/2014/02/24/what-every-javascript-developer-should-know-about-floating-point-numbers/). Let's skip the boring math and focus on working knowledge.

DOs

  • Keep in mind that JS has only one numerical type (typeof 4 = "number")
  • use external libraries like BigDecimal.js, Math.js, Sinful.js

DON'Ts

  • toFixed and toPrecision return strings. Use them only for display purposes
  • awesome advice: “expect floating point rounding errors, and duct tape around it”. The advice then follows on to say – if you expect 0.1 to be 0.10000000000000001 then work as if you’re working with 0.10000000000000001 all the time. I mean, wtf is with that kind of ridiculous advice??! Sorry, but that’s plain dumb.

That's all, folks!

Say Thanks
Respond