Quiz

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

Topics
JavaScript
Edit on GitHub

TL;DR

In JavaScript, you can convert a string to a number using several methods. The most common ones are Number(), parseInt(), parseFloat(), and the unary plus operator (+). For example, Number("123") converts the string "123" to the number 123, and parseInt("123.45") converts the string "123.45" to the integer 123.


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

Using the Number() function

The Number() function converts a string to a number. It can handle both integer and floating-point numbers.

let str = '123';
let num = Number(str); // 123
let floatStr = '123.45';
let floatNum = Number(floatStr); // 123.45

Using the parseInt() function

The parseInt() function parses a string and returns an integer. It can also take a second argument, the radix (base) of the numeral system to be used.

let str = '123';
let num = parseInt(str); // 123
let floatStr = '123.45';
let floatNum = parseInt(floatStr); // 123
let binaryStr = '1010';
let binaryNum = parseInt(binaryStr, 2); // 10

Using the parseFloat() function

The parseFloat() function parses a string and returns a floating-point number.

let floatStr = '123.45';
let floatNum = parseFloat(floatStr); // 123.45

Using the unary plus operator (+)

The unary plus operator can be used to convert a string to a number. It is a shorthand method and works for both integers and floating-point numbers.

let str = '123';
let num = +str; // 123
let floatStr = '123.45';
let floatNum = +floatStr; // 123.45

Handling non-numeric strings

If the string cannot be converted to a number, these methods will return NaN (Not-a-Number).

let invalidStr = 'abc';
let num = Number(invalidStr); // NaN
let intNum = parseInt(invalidStr); // NaN
let floatNum = parseFloat(invalidStr); // NaN
let unaryNum = +invalidStr; // NaN

Further reading

Edit on GitHub