How do you convert a string to a number in javascript?

There are two main ways to convert a string to a number in javascript. One way is to parse it and the other way is to change its type to a Number. All of the tricks in the other answers (e.g. unary plus) involve implicitly coercing the type of the string to a number. You can also do the same thing explicitly with the Number function.

Parsing

var parsed = parseInt("97", 10);

parseInt and parseFloat are the two functions used for parsing strings to numbers. Parsing will stop silently if it hits a character it doesn't recognise, which can be useful for parsing strings like "92px", but it's also somewhat dangerous, since it won't give you any kind of error on bad input, instead you'll get back NaN unless the string starts with a number. Whitespace at the beginning of the string is ignored. Here's an example of it doing something different to what you want, and giving no indication that anything went wrong:

var widgetsSold = parseInt("97,800", 10); // widgetsSold is now 97

It's good practice to always specify the radix as the second argument. In older browsers, if the string started with a 0, it would be interpreted as octal if the radix wasn't specified which took a lot of people by surprise. The behaviour for hexadecimal is triggered by having the string start with 0x if no radix is specified, e.g. 0xff. The standard actually changed with ecmascript 5, so modern browsers no longer trigger octal when there's a leading 0 if no radix has been specified. parseInt understands radixes up to base 36, in which case both upper and lower case letters are treated as equivalent.

Changing the Type of a String to a Number

All of the other tricks mentioned above that don't use parseInt, involve implicitly coercing the string into a number. I prefer to do this explicitly,

var cast = Number("97");

This has different behavior to the parse methods (although it still ignores whitespace). It's more strict: if it doesn't understand the whole of the string than it returns NaN, so you can't use it for strings like 97px. Since you want a primitive number rather than a Number wrapper object, make sure you don't put new in front of the Number function.

Obviously, converting to a Number gives you a value that might be a float rather than an integer, so if you want an integer, you need to modify it. There are a few ways of doing this:

var rounded = Math.floor(Number("97.654"));  // other options are Math.ceil, Math.round
var fixed = Number("97.654").toFixed(0); // rounded rather than truncated
var bitwised = Number("97.654")|0;  // do not use for large numbers

Any bitwise operator (here I've done a bitwise or, but you could also do double negation as in an earlier answer or a bitshift) will convert the value to a 32bit integer, and most of them will convert to a signed integer. Note that this will not do want you want for large integers. If the integer cannot be represented in 32bits, it will wrap.

~~"3000000000.654" === -1294967296
// This is the same as
Number("3000000000.654")|0
"3000000000.654" >>> 0 === 3000000000 // unsigned right shift gives you an extra bit
"300000000000.654" >>> 0 === 3647256576 // but still fails with larger numbers

To work correctly with larger numbers, you should use the rounding methods

Math.floor("3000000000.654") === 3000000000
// This is the same as
Math.floor(Number("3000000000.654"))

Bear in mind that coeercion understands exponential notation and Infinity, so 2e2 is 200 rather than NaN, while the parse methods don't.

Custom

It's unlikely that either of these methods do exactly what you want. For example, usually I would want an error thrown if parsing fails, and I don't need support for Infinity, exponentials or leading whitespace. Depending on your usecase, sometimes it makes sense to write a custom conversion function.

Always check that the output of Number or one of the parse methods is the sort of number you expect. You will almost certainly want to use isNaN to make sure the number is not NaN (usually the only way you find out that the parse failed).

How do you convert a string to a number in javascript?

Sanchithasr

Posted on Dec 16, 2020 • Updated on Aug 19, 2021

1. Using parseInt()

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned.
This method has a limitation though. If you parse the decimal number, it will be rounded off to the nearest integer value and that value is converted to string. One might need to use parseFloat() method for literal conversion.

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

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

Enter fullscreen mode Exit fullscreen mode

2. Using Number()

Number() can be used to convert JavaScript variables to numbers. We can use it to convert the string too number.
If the value cannot be converted to a number, NaN is returned.

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

Enter fullscreen mode Exit fullscreen mode

3. Using Unary Operator (+)

The unary plus operator (+) precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

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

Enter fullscreen mode Exit fullscreen mode

4. Using 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

Enter fullscreen mode Exit fullscreen mode

5. Using Math.floor()

The Math.floor() function returns the largest integer less than or equal to a given number. This can be little tricky with decimal numbers since it will return 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

Enter fullscreen mode Exit fullscreen mode

6. Multiply with number

Multiplying the string value with the 1 which won’t change the value and also it will be converted to number by default.

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

Enter fullscreen mode Exit fullscreen mode

7. Double tilde (~~) Operator

We can use the double tilde operator to convert the string to number.

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

Enter fullscreen mode Exit fullscreen mode

Here is the comparison of the ways mentioned performance wise. Comment below if you know more methods.
Thank You

How can a string be converted to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.

How do I convert a string to a number in TypeScript?

Use the Number() object to convert a string to a number in TypeScript, e.g. const num1 = Number(str) . ... .
Use the parseInt() function to convert a string to a number, e.g. const num1 = parseInt(str) . ... .
To extract a number from a string in TypeScript, call the replace() method, e.g. str..

How do you convert to int in JavaScript?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.

What does number () in JavaScript do?

The Number() method converts a value to a number. If the value cannot be converted, NaN is returned.