How to Convert String to Number in JavaScript

As a programmer, it is common to work with both numbers and strings in your code.

In some cases, you may have a string that represents a number, but you need to perform arithmetic operations on it.

In such situations, you’ll need to convert the string to a number in JavaScript.

In this Javascript tutorial, we will explore different ways to convert a string to a number in JavaScript.


Using the Number() Function

The simplest and most straightforward way to convert a string to a number in JavaScript is by using the Number() function.

This function takes a string as an argument and returns a number representation of the string.

let stringNumber = '123';
let number = Number(stringNumber);
console.log(typeof number); // number

Using parseInt() Function

Another option for converting a string to a number in JavaScript is by using the parseInt() function.

This function takes two arguments: the string to be converted and the radix (base) of the number.

The radix argument is optional, and if omitted, it defaults to 10.

let stringNumber = '123';
let number = parseInt(stringNumber);
console.log(typeof number); // number

Using parseFloat() Function

If you have a string representing a floating-point number, you can use the parseFloat() function to convert it to a number.

This function works similarly to parseInt() and also takes an optional radix argument.

let stringNumber = '123.456';
let number = parseFloat(stringNumber);
console.log(typeof number); // number
</code>

Using Unary Plus Operator

The unary plus operator (+) can also be used to convert a string to a number in JavaScript.

This operator has a higher precedence than arithmetic operators and can be used to convert non-numeric values to numeric values.

let stringNumber = '123';
let number = +stringNumber;
console.log(typeof number); // number

Using Math.floor() and Math.ceil() Functions

The Math.floor() and Math.ceil() functions can also be used to convert a string to a number in JavaScript.

These functions return the largest integer less than or equal to a number, and the smallest integer greater than or equal to a number, respectively.

let stringNumber = '123.456';
let number = Math.floor(stringNumber);
console.log(typeof number); // number
let stringNumber = '123.456';
let number = Math.ceil(stringNumber);
console.log(typeof number); // number

Conclusion

In conclusion, converting a string to a number in JavaScript is a common task for a programmer.

With the methods discussed in this article, you can easily convert a string to a number in JavaScript.

Whether you need to use the Number() function, parseInt() function, parseFloat() function, unary plus operator, or Math.floor() and Math.ceil() functions, there is a solution available to meet your needs.