Friday, October 4, 2024
HomeWeb developmentQuick Tip: How to Convert a String to a Number in JavaScript

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); 
console.log(typeof str); 

const number = Number(str);
console.log(number); 
console.log(typeof 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); 
console.log(typeof str); 

const intNumber = parseInt(str);
console.log(intNumber); 
console.log(typeof intNumber); 

const floatNumber = parseFloat(str);
console.log(floatNumber); 
console.log(typeof floatNumber); 

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); 
console.log(+str); 
console.log(typeof +str); 

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:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments