How to Convert a String to a Number in JavaScript
Table of Contents
Numbers can be used in JavaScript in both strings and number form.
In some cases, we'll need to able to convert a string to a number so that we can use it in mathematical operations.
Thankfully, there are several built-in ways to do this in JavaScript.
In this post, we'll go over the two best ways to convert a string to a number in JavaScript.
Using the parseInt() method
The most straight-forward way to convert a string to a number is to use the parseInt()
method that is built-in.
This method just takes in a string and returns the number that it represents.
JAVASCRIPTconst string = "123";
const number = parseInt(string);
console.log(number);
BASH123
Keep in mind that because this only parses integers, it will not properly convert a string that contains a decimal point. Instead, the method will strip out the decimal point and return the integer.
If you pass it a non-number string, you will get back NaN
.
Using Number()
Another way to convert a string to a number is to use the Number()
method.
This method will take in a string and return the number that it represents.
JAVASCRIPTconst string = "123.45";
const number = Number(string);
console.log(number);
BASH123.45
Notably, when you pass it a string with decimals, it will return the number with the decimals, which is a useful benefit to know.
Like before, it will return NaN
if you pass it a non-number string.
Conclusion
In this post, we looked at the two best ways to go from a string of a number to an actual number.
While each one will get the job done, if you're aiming to preserve decimals, you'll need to use the Number()
method.
Thanks for reading and hope you have found this post helpful!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Vuex: Managing State in Vue