In JavaScript, you can convert a string to a number using many methods.
-
parseInt() function:
This function parses a string argument and returns an integer of the specified radix (base). If no radix is specified, it assumes the input is in base 10.
For example:
let stringNum = "100"; let number = parseInt(stringNum); // returns 100
-
parseFloat() function:
This function parses a string argument and returns a floating-point number. If the string cannot be converted to a number, it returns NaN.
For example:
let stringNum = "3.1415"; let number = parseFloat(stringNum); // returns 3.1415
-
Number () constructor:
This constructor can be used to convert a string to a number. It returns NaN if the input cannot be converted.
let stringNum = "10"; let number = Number(stringNum); // returns 10
-
Plus(+) operator:
Using plus(+) operator, we can convert any string to a number. If that string contains any non numeric character, then the converted value will be
NaN
.let stringNum = "50"; let number = +stringNum; // returns 50
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.