Quiz

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

Topics
JavaScript

TL;DR

Use Number(value) when the whole string must represent a number. Use parseInt(value, radix) or parseFloat(value) when intentionally accepting a numeric prefix such as '12px'; they stop at the first invalid character. Check the result with Number.isNaN() or, for finite application values, Number.isFinite(). Remember that Number('') and Number(' ') are 0, so validate required input before conversion.


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);
console.log(num); // 123
let floatStr = '123.45';
let floatNum = Number(floatStr);
console.log(floatNum); // 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);
console.log(num); // 123
let floatStr = '120.45';
let floatNum = parseInt(floatStr);
console.log(floatNum); // 120
let binaryStr = '1010';
let binaryNum = parseInt(binaryStr, 2);
console.log(binaryNum); // 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);
console.log(floatNum); // 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;
console.log(num); // 123
let floatStr = '123.45';
let floatNum = +floatStr;
console.log(floatNum); // 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';
console.log(Number(invalidStr)); // NaN
console.log(parseInt(invalidStr)); // NaN
console.log(parseFloat(invalidStr)); // NaN
console.log(+invalidStr); // NaN

The conversion methods are intentionally different:

console.log(Number('12px')); // NaN: the entire string is not numeric
console.log(parseInt('12px', 10)); // 12: parses a numeric prefix
console.log(Number('')); // 0
console.log(parseInt('', 10)); // NaN
console.log(Number('0x10')); // 16

Always pass the radix to parseInt() when the expected base is known. Do not test for NaN with value === NaN; NaN is unequal to itself.

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

What does this code log?

console.log(Number('12px'), parseInt('12px', 10), Number(' '));