Convert From a String to a Number

Question:

If you have a variable with a numeric value represented as a string, how do you convert it to a numeric type in order to use it in a mathematical function? For example, I want to convert:

x = "5" 

to

x = 5

Answer:

Even though JavaScript is an untyped language, meaning that you don’t have to explicitly declare your variables to be a specific type, there are times when you’ll need to explicitly convert from a string to a number or vice-versa. JavaScript is generally pretty smart about converting from a number to a string when required and will usually do the conversion for you. However, going from a string to a number will often require some intervention on your part. Luckily, JavaScript’s parseInt() and parseFloat() functions make the job pretty easy for integers and floats (numbers with decimals), respectively.

If the variable x contains the string “5” then this code will convert it to its number equivalent and assign it to the variable y:

y = parseInt(x);

These functions are also fairly tolerant of bad data and will convert from a string to a number for as many numeric characters as they find. For example, if you pass “5.2abc” to the parseFloat() function it’ll return the number 5.2.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: