How do you convert a string to a number in JavaScript?
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.
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.
Using the parseFloat()
function
The parseFloat()
function parses a string and returns a floating-point number.
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.
Handling non-numeric strings
If the string cannot be converted to a number, these methods will return NaN
(Not-a-Number).