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.

 

Like Riding a Bike?

bike

I recently took a little bit of time off of studying JavaScript to attempt the construction of some actual websites. So now that I had a couple of sites under my belt I decided to dive back into the Free Code Camp Front End Certificate.

Have you ever left a video game for a couple of months and then come back with absolutely zero idea of what is going on? Because that’s exactly what happened to me, I had no idea how to create a function, looping was lost on me and I couldn’t even remember the difference between an array and an object. Studying JavaScript is just like riding a bike… if that bike had no wheels and a cat for a seat.

But complete and utter despair at my lack of ability isn’t something that gets me down for (too) long and after a couple of weeks of persevering I was running through the intermediate problems with increasing confidence. As intimidating as stuff like this can be when you first look at it, once you have a basic grasp of the fundamentals, the world is your oyster.

I hate that saying… I don’t even like oysters.

The world is your oyster deep fried mars bar.

Fixed.