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

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

There are many situations where a number can 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 automatically perform the string-to-number conversion for you. However, sometimes you need to extract a number from a string, or have more control over how the conversion is performed.

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

convert a string to 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); 

while logging the value of str and its type in 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 a working example in the following CodePen demo.

see pen
Convert a string to number with number()
by sitepoint (@SitePoint,
Feather codepen,

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

Convert a string to number using parseInt() and parseFloat()

using another approach parseInt() And parseFloat(), as you can tell, parseInt() parses a string into an integer, whereas parseFloat() Parses a string with decimal points into a number.

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); 

same as the first approach while logging the value of str and its type in console, the result is 10.1 as a string and string respectively. However, when analyzing str using the parseIntThe value of intNumber It happens 10 and its type number,

On the other hand, while parsing str using the parseFloatThe value of floatNumber It happens 10.1 as a number and its type is number,

You can see a working example in the following CodePen demo.

see pen
Convert string to number with parseInt() and parseFloat()
by sitepoint (@SitePoint,
Feather codepen,

second argument to ParseInt

parseInt() Takes a second argument that specifies the base of the number to be parsed from the string. This argument is actually optional, but it is highly recommended that you always provide it.

Without this second argument, parseInt automates Formula trace. That is, it finds the base of a number by its format in the string. beginning of a number 0x either 0X is assumed to be hexadecimal (base 16), and all other numbers are assumed to be decimal.

So, for example, if you were to call parseInt("08"), the input value will be treated as an octal number; But 8 is not an octal digit (because octal numbers are 0–7), so the function will return a value of zero, not eight.

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

convert a string to number using unary plus

A third way to convert a string to a number is to use unary plus (+, If unary plus is used before the operand, it tries to convert it to a number. So, if the operand is a string containing a number, 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 type stras expected, it is string, However, when you log the value of +str and its types, 10 And number are logged into the console respectively.

You can see a working example in the following CodePen demo.

see pen
Using unary to convert strings
by sitepoint (@SitePoint,
Feather codepen,

How to handle non-numeric characters in strings

It is important to note the cases where a string may contain characters other than numbers and how each approach handles this.

when using Number()If the string contains characters other than numbers, beginning with plus (+) and minus (-) signs, or decimal points, the value returned is the special value NaN (not-a-number). NaN is a global property that represents Not-a-Number. returned by some numerical operations When the operands or parameters of those operations are either not numbers or cannot 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 skips the rest of the characters and takes the number found at the beginning of the string. However, if the string begins with characters other than numbers, leading plus (+) and minus (-) signs, or decimal points, the value returned is the special value NaN (not-a-number).

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

see pen
Difference Between Number and ParseInt
by sitepoint (@SitePoint,
Feather codepen,

as you can see, Number() Returns NaN since the string is joined px, Although, parseInt() Return 10 Since it is at the beginning of the string.

You can check if a value is NaN or not by using a global function isNaN(),

conclusion

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

On the other hand, parseInt() And parseFloat() There are more flexible approaches in terms of handling other characters in the number. However, in some cases these two functions cannot be used interchangeably. For example, if the number in the string is a float and you use parseInt()You will get wrong value comparing string.

Although using unary is easier, it can reduce the readability of your code. Whichever method you choose, it is important to pay attention to cases where the returned result may be NaN.

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

Leave a Reply