Quick Tip: How to Convert a String to a Number in JavaScript

Share this article

Quick Tip: How to Convert a String to a Number in JavaScript

In JavaScript, there are many ways to convert between data types. We’ve already covered how to convert a number to a string. In this short tutorial, we’ll look at how you can convert a string to a number in JavaScript.

There are many situations where a number might be stored as a string. For example, values received from a form element are always strings.

In general, you can treat a JavaScript string that contains a number (and only a number) as if it were a number, and JavaScript will perform the string-to-number conversion for you automatically. However, sometimes you need to extract a number from a string, or exercise more control over how the conversion is done.

In this quick tip, we’ll cover three ways to convert a string to a number.

Convert a String to a Number Using Number

The most direct way to convert a string to a number in JavaScript is to use the built-in Number constructor function. For example:

const str = "10"
console.log(str); // "10"
console.log(typeof str); // "string"

const number = Number(str);
console.log(number); // 10
console.log(typeof number); // "number"

When logging the value of str and its type in the console, the result is 10 as a string and string respectively. After converting it, the result is 10 as a number and number respectively.

You can see the example in action in the following CodePen demo.

See the Pen Convert a String to a Number with Number() by SitePoint (@SitePoint) on CodePen.

Please note that if you pass a non-numeric string to a number, NaN will be returned.

Convert a String to a Number Using parseInt() and parseFloat()

Another approach is using parseInt() and parseFloat(). As you can tell, parseInt() parses a string to an integer, whereas parseFloat() parses a string to a number with decimal points.

For example:

const str = "10.9"
console.log(str); // "10.9"
console.log(typeof str); // "string"

const intNumber = parseInt(str);
console.log(intNumber); // 10
console.log(typeof intNumber); // "number"

const floatNumber = parseFloat(str);
console.log(floatNumber); // 10.9
console.log(typeof floatNumber); // "number"

Similar to the first approach, when logging the value of str and its type in the console, the result is 10.1 as a string and string respectively. However, when parsing str using parseInt, the value of intNumber becomes 10 and its type is number.

On the other hand, when parsing str using parseFloat, the value of floatNumber becomes 10.1 as a number and its type is number.

You can see the example in action in the following CodePen demo.

See the Pen Convert String to Number with parseInt() and parseFloat() by SitePoint (@SitePoint) on CodePen.

parseInt’s Second Argument

parseInt() takes a second argument that specifies the base of the number to be parsed from the string. This argument is in fact optional, but it’s highly recommend that you always provide it.

Without this second argument, parseInt performs automatic radix detection. That is, it detects the base of a number by its format in the string. A number beginning 0x or 0X is considered to be hexadecimal (base 16), and all other numbers are considered to be decimal.

So, for example, if you were to call parseInt("08"), the input value would be considered an octal number; but 8 is not an octal digit (because octal numbering is 0–7), so the function would return a value of zero, not eight.

To avoid any confusion, always specify the base when using parseInt().

Convert a String to a Number Using Unary Plus

The third way to convert a string to a number is to use the unary plus (+). If the unary plus is used before an operand, it attempts to convert it to a number. So, if the operand is a string that contains a number, the unary plus will convert it to a number.

For example:

const str = "10";
console.log(typeof str); // "string"
console.log(+str); // 10
console.log(typeof +str); // "number"

When you log the type of str, as expected, it’s string. However, when you log the value of +str and its type, 10 and number are logged in the console respectively.

You can see the example in action in the following CodePen demo.

See the Pen Using Unary to Convert Strings by SitePoint (@SitePoint) on CodePen.

How to Handle Non-Numeric Characters in Strings

It’s important to take into account cases where a string might contain characters other than numbers and how each approach handles this.

When using Number(), if the string contains characters other than numbers, plus(+) and minus(-) signs at the beginning, or decimal points, the returned value is the special value NaN (Not-a-Number). NaN is a global property that represents Not-a-Number. It’s returned by some numerical operations when the operands or parameters of those operations are either not numbers or can’t be used for that specific mathematical operation.

On the other hand, parseInt() and parseFloat() parse the string if the number is at the beginning of the string. It drops the rest of the characters and takes the number encountered at the beginning of the string. However, if the string starts with characters other than numbers, plus(+) and minus(-) signs at the beginning, or decimal points, the returned value is the special value NaN (Not-a-Number).

You can see it in action in the following CodePen demo.

See the Pen Difference Between Number and parseInt by SitePoint (@SitePoint) on CodePen.

As you can see, Number() returns NaN since the string contains px. However, parseInt() returns 10 since it’s at the beginning of the string.

You can check if a value is NaN using the global function isNaN().

Conclusion

This short tutorial has covered three ways to convert a string to a number in JavaScript. Number() can convert a string to a number, whether it’s a float or an integer. However, if the string contains other characters, it returns NaN. This is helpful if you want to ensure a strict conversion of the string.

On the other hand, parseInt() and parseFloat() are more flexible approaches in terms of handling other characters in the number. However, these two functions can’t be used interchangeably in some cases. For example, if the number in the string is a float and you use parseInt(), you’ll get an incorrect value compared to the string.

Although the unary is easy to use, it can reduce readability of your code. Whichever method you choose, it’s important to look out for cases where the result returned might be NaN.

If you found this article useful, you may also enjoy the following:

FAQs about Converting String to Number in JavaScript

What are the different methods to convert a string to a number in JavaScript?

There are several methods to convert a string to a number in JavaScript. The most common ones include the Number() function, the parseInt() function, the parseFloat() function, and the unary plus (+) operator. Each method has its own use cases and can be used depending on the specific requirements of your code.

How does the Number() function work in JavaScript?

The Number() function in JavaScript can be used to convert a string to a number. It takes a string as an argument and returns a number. If the string cannot be converted into a number, it returns NaN (Not a Number). For example, Number(“1234”) would return 1234, while Number(“1234abc”) would return NaN.

What is the difference between parseInt() and parseFloat() in JavaScript?

Both parseInt() and parseFloat() are used to convert strings to numbers in JavaScript. The difference lies in the type of number they return. parseInt() returns an integer, while parseFloat() returns a floating-point number. For example, parseInt(“123.45”) would return 123, while parseFloat(“123.45”) would return 123.45.

How can I use the unary plus (+) operator to convert a string to a number in JavaScript?

The unary plus (+) operator can be used to convert a string to a number in JavaScript. It is placed before the string, like this: + “1234”. This would return the number 1234. If the string cannot be converted into a number, it returns NaN.

What happens if I try to convert a non-numeric string to a number in JavaScript?

If you try to convert a non-numeric string to a number in JavaScript using any of the methods mentioned above, it will return NaN, which stands for Not a Number.

How can I check if the conversion from string to number was successful in JavaScript?

You can use the isNaN() function in JavaScript to check if the conversion from string to number was successful. This function returns true if the argument is Not a Number (NaN), and false otherwise.

Can I convert a string to a number in JavaScript without using any built-in functions?

Yes, it is possible to convert a string to a number in JavaScript without using any built-in functions, although it is more complex and not recommended for beginners. One way is to use a loop to iterate through each character in the string and calculate the number using the ASCII values of the digits.

How can I convert a string to an integer in JavaScript?

You can convert a string to an integer in JavaScript using the parseInt() function. This function takes a string as an argument and returns an integer. If the string cannot be converted into an integer, it returns NaN.

How can I convert a string to a floating-point number in JavaScript?

You can convert a string to a floating-point number in JavaScript using the parseFloat() function. This function takes a string as an argument and returns a floating-point number. If the string cannot be converted into a floating-point number, it returns NaN.

What is the best method to convert a string to a number in JavaScript?

The best method to convert a string to a number in JavaScript depends on your specific requirements. If you need an integer, use parseInt(). If you need a floating-point number, use parseFloat(). If you’re not sure, use the Number() function or the unary plus (+) operator, as they can handle both integers and floating-point numbers.

Dianne PenaDianne Pena
View Author

Dianne is SitePoint's newsletter editor. She especiallly loves learning about JavaScript, CSS and frontend technologies.

data typesJS Quick Tipsstrings
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form