Mikke.Learns

Converting a string to a number in javascript

January 23rd, 2019

At work we develop, design for and install digital signage screens for our customers. A couple of days ago, I was asked to round the wind speed number in the weather forecast displayed on a screen for one of our customers.

weather

The client did not want to display the wind speed with descimals.

The weather data was fetched via an API, and the programming was pretty easy. I had to collect all the instances of wind speed, convert the strings to numbers, round it and put it back in:

let windSpeedNumbers = document.querySelectorAll(.windspeed); for (let i = 0; i < numbers.length; i++) { windSpeedNumbers[i].innerHTML = Number(Math.round(windSpeedNumbers[i].innerHTML)); }

weather2

This is what greeted me today. A forecast with no wind speed.

No one had tinkered with the code or changed the template. I deleted the code, wrote it again, and renamed the class of the DOM objects without luck.

While Number() resulted in a “NaN”, parseInt() and parseFloat() gave me a number, but it was just the first decimal; 1.78 returned 1. That’s when I discovered something interesting.

for (var i = 0; i < numbers.length; i++) { let num = Number(windSpeedNumbers[i].innerHTML); console.log(typeof num); // Console says: "Number" console.log(Math.round(num)); // Console says: "NaN" }

In the above code, Javascript tells me that the variable num is a number, but when rounding it, I still got “NaN”. That’s when I realized that the type of num was a number, but the actuall number was not. And so even if the variable type was number, Javascript didn’t find a number inside it.

After a lot of trial and error, I had (another) facepalm moment (there are a lot of those when learning to code).

The data in the API had changed. Can you spot the difference from this image and the first?

weather3

There was now a comma (,) and not a dot (.) separating the numbers.

After realizing this, all I had to do was to convert the comma back to a dot.

for (var i = 0; i < numbers.length) { let num = windSpeedNumbers[i].innerHTML; num = Math.round(num.replace(/,/g, '.')); }

What did I learn?
  • parseInt() converts a string into an integer (a whole number). It takes two arguments. The first is the string to convert. The second is the radix (the base in mathematical numeral systems), a number between 2 - 36. It should always be provided.

  • parseFloat() converts a string into a number with decimal points.

  • Number() converts a string to a number.

let num = “3.14”; parseInt(num, 10); // 3 parseFloat(num); // 3.14 Number(num); // 3.14 let num2 = 12.3; parseInt(num2, 10); // 12 parseFloat(num2); // 12.3 Number(num2); // NaN

As we can see from the code above, Number() is a less consistent choice.