. Advertisement .
..3..
. Advertisement .
..4..
In this tutorial, you will learn how to convert a string to a number in JavaScript. This is an important task for many applications, especially when working with data that needs to be stored in a numeric format. There are several ways to do this, and the one that you choose depends on the situation.
Ways to convert a String to Number in JavaScript
1) Number() function
The first way is to use the built-in Number() function. This function takes a string as input and converts it into a number. For example, if the string is “2”, then Number() will return 2. You can also use this function to convert strings that contain numbers (such as “3.14”), as well as other types of strings (such as “abc”).
Number("12"); // returns 12
Number(" 15 "); // returns 15
Number("14.53"); // returns 14.53
2) parseInt() function
Another way to convert strings into numbers is by using the parseInt() function. This function takes a string as input and converts it into an integer value. For example, if the string is “42”, then parseInt() will return 42. The downside of using parseInt() is that it doesn’t work with all types of strings. For example, it won’t work with strings that contain special characters (like quotes).
testString = '213'
console.log(parseInt(testString)) // expected result: 213
x = 13.23
console.log(parseInt(x)) // expected result: 13
3) parseFloat() function
JavaScript provides a parseFloat() function to convert a number into a float.
ParseFloat() takes a string in the form of “1.23” and returns an object with the following properties:
parseFloat(str) { return Number(str); }
parseInt(str, radix) { return parseInt(str, radix | 0); }
It is only the initial number that will be returned. Spaces are allowed.
parseFloat("8"); // returns 8
parseFloat("18.32"); // returns 18.32
parseFloat("12 22 40"); // returns 12
parseFloat("12 years"); // returns 12
parseFloat("years 12"); // returns NaN
Conclusion
Above are 3 useful ways to convert a String to Number in JavaScript, hope it can help you. Don’t forget to leave a comment below, it still has many other ways.
Leave a comment