JavaScript and Decimal Places, A Shortcut to Insanity

Uhhhh, who invited Gottfried to the Party?

Uhhhh, who invited Gottfried to the Party?

 

So after spending a couple of days trying to work through the freeCodeCamp algorithm script Exact Change I came across a rather unexpected issue.

In JavaScript (0.1 + 0.2 === 0.3) is false.

After running around in circles crying foul and threatening my laptop with a number of things that would break the Geneva Convention I had a look around the internet to see if anyone else had experienced the same problem.

It turns out that my anger was misdirected at my laptop (apologies); in fact it should have been aimed at a young man by the name of Gottfried Lebiniz, the inventor of binary.

The problem is that computers speak in the language called binary (a sequence of Zeros and Ones) meaning that numbers have to be stored in a format called “binary floating point”. This format is designed in such a way that it is unable to actually represent the true value of some decimal places.

In JavaScript 0.1 + 0.2 actually equals 0.3000000000000004.

Confused? Yeah me too, until I chanced across this video, it’s about 30 mins long but if you can get through it, you’ll no longer be preparing to hang your computer’s toes over some burning coals, but quickly googling good old Gottfried in order to put a curse upon him (he died in 1716 just fyi, I guess someone else got to him first). Also you might just learn a thing or two about how binary floating point works.

 

 

If you’d like some more information on the floating point format I’d recommend the website http://floating-point-gui.de.

As for the freeCodeCamp’s Exact Change … move over Ben Affleck, Math.round() has just become my new best friend.