How can you convert a string to a number in JavaScript?

In JavaScript, there are several methods to convert a string to a number. Here are some commonly used techniques:

parseInt() function:

The parseInt() function is used to parse a string and convert it to an integer. It takes two arguments: the string to be converted and an optional radix (base) value.

Example:

const stringNum = “42”;

const number = parseInt(stringNum);

console.log(number); // Output: 42

In this example, the parseInt() function is used to convert the string “42” to the integer 42. If the string cannot be converted to a number, parseInt() will return NaN.

parseFloat() function:

The parseFloat() function is similar to parseInt(), but it is used to convert a string to a floating-point number (decimal number).

Example:

const stringNum = “3.14”;

const number = parseFloat(stringNum);

console.log(number); // Output: 3.14

Here, the parseFloat() function converts the string “3.14” to the floating-point number 3.14.

Unary Plus Operator:

Applying the unary plus operator (+) to a string can also convert it to a number.

Example:

const stringNum = “42”;

const number = +stringNum;

console.log(number); // Output: 42

In this example, the unary plus operator converts the string “42” to the number 42.

Number() function:

The Number() function is a built-in JavaScript function that can be used to convert a string to a number.

Example:

const stringNum = “42”;

const number = Number(stringNum);

console.log(number); // Output: 42

Here, the Number() function converts the string “42” to the number 42.

It’s important to note that if the string cannot be parsed as a valid number, these conversion methods will return NaN (Not-a-Number). Therefore, it’s always a good practice to check the result when converting strings to numbers.

Additionally, be cautious when using parseInt() and parseFloat() with non-integer or non-decimal strings, respectively, as they may behave differently based on the provided radix or encounter unexpected results.

By utilizing these methods, you can easily convert strings to numbers in JavaScript, enabling you to perform mathematical calculations and manipulate numerical data.