← coderrocketfuel.com

How to Convert a String to a Number in Node.js

How do you convert a string to a number in Node.js?

You can convert a string to a number in Node.js using any of these three methods: Number(), parseInt(), or parseFloat().

In this article, we'll go over each method and how to use them in your code.

Let's get started!

Table of Contents

Method 1 - Number()

The first method we'll cover is the Number() constructor that takes a value as a parameter and attempts to convert it to a number. If the value passed to the Number() constructor can't be converted to a number, NaN is returned.

Here's an example of how you'd use it in your code:

// returns 25 (typeof === number)

We pass a string value of "25" to the Number() constructor and it returns a new number value of 25. If you checked the typeof value for the new value, you'd find that it was transformed successfully from a string to a number.

Here are some more examples with different variations of strings passed as arguments:

Number("25")             // returns 25
Number("25.51")          // returns 25.51
Number("25px")           // returns NaN
Number("25.5something")  // returns NaN

Pretty easy to work with, right?

Method 2 - parseInt()

The parseInt() is a function that parses a string and returns an integer with a specific radix. The function takes both a string and an optional radix integer value as parameters.

Here's a code example:

// returns 25 (typeof === number)

We give the parseInt() function a "25" string as a parameter and it returns a value of 25. And the new value is a number instead of a string.

Here are some additional examples with other variations of strings:

parseInt("25")             // returns 25
parseInt("25.51")          // returns 25
parseInt("25px")           // returns 25
parseInt("25.5something")  // returns 25

Unlike the previous Number() method, notice that all of the four example strings were converted to a 25 number value. In those cases, the Number() method returned a value of NaN instead.

Method 3 - parseFloat()

The last method we'll go over is the parseFloat() function that takes a string and converts it to a number with decimals (known as a point number).

Here's what it looks like in code:

// returns 25 (typeof === number)

Just like the previous two examples, the parseFloat() function takes a string of "25" and converts it into a number value of 25.

And here are some additional examples using the same string variations as the other methods:

parseFloat("25")             // returns 25
parseFloat("25.51")          // returns 25.51
parseFloat("25px")           // returns 25
parseFloat("25.5something")  // returns 25.5

Notice that the results are very similar to the parseInt() method, besides the fact that parseFloat() conserves the decimal points on the string values it converts.