7 Ways to Convert Strings to Numbers in JavaScript

1. Use parseInt()

parseInt()Parses a string and returns an integer. Spaces are allowed. Only the first number is returned.
This approach has a limitation though. If you parse a decimal number, it will round to the nearest integer value and convert that value to a string . Might need to use parseFloat()method for text conversion.

myString = '129' 
console.log(parseInt(myString)) // expected result: 129

a = 12.22
console.log(parseInt(a)) // expected result: 12

2. Use Number()

Number()Can be used to convert JavaScript variables to numbers. We can use it to convert strings too numbers. Returns
if the value cannot be converted to a number .NaN

Number("10");          // returns 10
Number(" 10  ");       // returns 10
Number("10.33");       // returns 10.33

3. Use the unary operator (+)

The unary plus operator (  +) precedes and evaluates its operand, but attempts to convert it to a number if it has not already been.

const x = 25;
const y = -25;
console.log(+x); // expected output: 25
console.log(+y); // expected output: -25
console.log(+''); // expected output: 0

4. Use parseFloat()

parseFloat()Parses a string and returns a number. Spaces are allowed. Only the first number is returned.

parseFloat("10");        // returns 10
parseFloat("10.33");     // returns 10.33
parseFloat("10 20 30");  // returns 10
parseFloat("10 years");  // returns 10
parseFloat("years 10");  // returns NaN

5. Using Math.floor()

This Math.floor()function returns the largest integer less than or equal to the given number. This can be a bit tricky for decimal numbers, since it returns the value of the nearest integer as Number .

str = '1222'
console.log(Math.floor(str)) // returns 1222

a = 12.22
Math.floor(a) // expected result: 12

6. Multiply numbers

Multiplying a string value 1does not change the value, and it is converted to a number by default.

str = '2344'
console.log(str * 1) // expected result: 2344

7. Double tilde (~~) operator

We can convert a string to a number using the double tilde operator.

str = '1234'
console.log(~~str) // expected result: 1234
negStr = '-234'
console.log(~~negStr) // expected result: -234

Here is a comparison of the mentioned ways in terms of performance. If you know of more ways, please comment below.
Thank you

Guess you like

Origin blog.csdn.net/allway2/article/details/124955087