How to Convert Strings to Numbers in JavaScript

In this post, we'll learn how to convert strings to numbers in JavaScript.
Let's look at the three different ways you can convert strings to numbers.
parseInt()
The best way to convert a string to a number is to use the parseInt()
function.
This function accepts two parameters, the string to convert and the optional radix
.
You can think of the radix
as the base of the number system, the default being 10
.
Here's an example of how to use the parseInt()
function:
const number = parseInt("123", 10);
console.log(number); // 123
As mentioned before, the radix
is optional, so this also works:
const number = parseInt("123");
console.log(number); // 123
parseFloat()
The parseFloat()
function is similar to parseInt()
, except it will convert the string to a floating point number, basically a number with decimal points.
Like with parseInt()
, you can pass a radix
, which is optional.
const number = parseFloat("123.456", 10);
console.log(number); // 123.456
It will also return the same value without the radix
parameter:
const number = parseFloat("123.456");
console.log(number); // 123.456
Number()
The third way to convert a string to a number is by using the Number()
function.
You can think of the Number()
function as a combination of the previous two functions, except it will always use the 10
radix.
That means if you pass it a string with a decimal point, it will convert it to a floating point number, and if not, it will convert it to an integer.
Here's an example of using Number()
:
const number1 = Number("123.456");
const number2 = Number("123");
console.log(number1); // 123.456
console.log(number2); // 123
Conclusion
We've covered three different ways to convert a string to a number in JavaScript.
Hopefully, you've found these ways useful for your use-case.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!