Here are the 7 ways to convert a string to a number in JavaScript.
- Using the Number() function
- Using the parseInt() function
- Using the parseFloat() function
- Using the unary operator(+)
- Using the Math.floor() function
- Using the Double tilde (~~) Operator
- Using the Multiplication
Method 1: Using the Number() function
The easiest way to convert a string to number is to use the Number() function.
Visual Representation
Example
let price = "479";
let product = "PlayStation";
console.log(Number(price));
console.log(Number(product)) ;
Output
479
NaN
Method 2: Using the parseInt() function
You can use the parseInt() function that parses a string and returns an integer.
Visual Representation
Example
let price = "479";
let product = "PlayStation";
console.log(parseInt(price));
console.log(parseInt(product));
Output
479
NaN
Method 3: Using the parseFloat() function
The parseFloat() method parses a string and returns a floating-point number.
Visual Representation
Example
let price = "479.45";
console.log(parseFloat(price, 10));
Output
479.45
Method 4: Using the + Unary Operator
The unary plus operator can convert a string to a number if the string is a valid numerical representation. The operator will go before the operand.
Visual Representation
Example
let price = +"479";
console.log(price);
Output
479
Method 5: Using the Math floor() function
The Math.floor() function that rounds down and returns the largest integer less than or equal to a given number.
Visual Representation
Example
let floor = Math.floor("479.45");
console.log(floor);
Output
479
Method 6: Using the Double tilde (~~) Operator
Visual Representation
Example
let price = "479";
console.log(parseInt(~~price));
Output
479
Method 7: Multiply with the number
Visual Representation
Multiplying the string value with the 1 won’t change the value; it will be converted to a number by default.
Example
let price = "479";
console.log(price * 1);
Output
479