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!
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications