convert string to number in javascript

To convert a string to a number in JavaScript, you can use the parseInt() or parseFloat() functions.

The parseInt() function is used to parse a string and return an integer. It takes two arguments, the first being the string to be parsed and the second being the radix (or base) of the number. If the second argument is omitted, the function assumes a radix of 10.

index.tsx
let str = "42";
let num = parseInt(str);
console.log(num); // Output: 42
73 chars
4 lines

The parseFloat() function is used to parse a string and return a floating-point number. It only takes one argument, the string to be parsed.

index.tsx
let str = "3.14";
let num = parseFloat(str);
console.log(num); // Output: 3.14
79 chars
4 lines

In both cases, if the string cannot be converted into a number, the functions will return NaN (which stands for "Not a Number").

gistlibby LogSnag