How to Convert Strings to Numbers in JavaScript
Table of Contents
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:
JAVASCRIPTconst number = parseInt("123", 10);
console.log(number); // 123
As mentioned before, the radix
is optional, so this also works:
JAVASCRIPTconst 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.
JAVASCRIPTconst number = parseFloat("123.456", 10);
console.log(number); // 123.456
It will also return the same value without the radix
parameter:
JAVASCRIPTconst 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()
:
JAVASCRIPTconst 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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io