To convert a value to a number in JavaScript

7 ways to convert a String to Number in JavaScript

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 

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 

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 

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 

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 

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 

7. Double tilde (~~) Operator

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

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

Читайте также:  Html center page contents

Top comments (17)

The double tilde method is actually something I never thought about, but is worth explaining.

The double tilde «operator» is not as much as an operator as it’s a double bitwise negation.

Let’s cast ’64’ to 64 using this method, so we do ~~’64’ . First we will evaluate ~’64’ . As bitwise operations work on binary, ’64’ is cast to a number. So ~64 .

64 in binary is 01000000 . ~ will negate all the bits so it becomes 10111111 , which is -65 since numbers in JavaScript are signed. Now we negate it again, which becomes 01000000 , which is 64 in decimal.

I previously stated that 10111111 is -63 , which is incorrect. It’s actually -65 . Sorry about that.

14 likes Like Comment button

Источник

Javascript: Converting String to Number?

parseFloat can be used for floating point numbers. Unary + is a third option: str = +str .

That being said, however, the term «type» is used quite loosely in JavaScript. Could you explain why are you concerned with variable’s type at all?

Thanks, Fyodor. I’m trying to extract the number from a string using a regexp, and it returns a string, so I would want to convert it to a number so that it can be processed.

No, the radix cannot be omitted, and there is no default. If you ommit it the vm will try to guess the radix causing eg. 010 to be interpreted not as 10 but as 8.

@Warrantica: Ok, that seems legit. What confused me was the expression «change the type of variable». That’s not what one usually would want to do. A more correct phrasing for your question would be, «how do I convert a string to number»?

I’ve done a quick search on radix. The «begin with 0 means octal» is depreciated, but if it begins with «0x», it interpret as hexadecimal, though.

about a decade late, but: use parseFloat instead of parseInt . They yield the same Number , but parseFloat will cover all normal use-cases without needing a radix, or if/then checks just because there might be a decimal point.

There are three ways to do this:

str = parseInt(str, 10); // 10 as the radix sets parseInt to expect decimals 
str = Number(str); // this does not support octals 
str = +str; // the + operator causes the parser to convert using Number 

My previous question was in error. bclary.com/2004/11/07/#a-11.4.6 The + operator doesn’t do what it does in other languages (foo > 0 ? foo : -foo;)

@Consp. I’m not following you, whats the relevance? But for your sample code you need to use — or ++

    The unary + operator: value = +value will coerce the string to a number using the JavaScript engine’s standard rules for that. The number can have a fractional portion (e.g., +»1.50″ is 1.5 ). Any non-digits in the string (other than the e for scientific notation) make the result NaN . Also, +»» is 0 , which may not be intuitive.

So, pick your tool to suit your use case. 🙂

Источник

How to convert a value to a number in JavaScript?

JavaScript has introduced Number(), parseInt(), parseFloat() methods to convert a value into a number and also we can achieve it by using (+) unary operator. These mentioned methods can convert number strings to numbers and Boolean values to 1’s or 0’s. Let’s us discuss these above mentioned methods briefly.

We’ll discuss the 4 possible ways to convert a value to a number with an example each.

Example 1

The following is an example program to convert a value to a number using Number() method.

     

To convert a value to a number in JavaScript using Number()

On executing the above code, the following output is generated.

Example 2

The following is an example program to convert a value to a number using parseInt() method.

     

To convert a value to a number in JavaScript using parseInt()

On executing the above code, the following output is generated.

Example 3

The following is an example program to convert a value to a number using parseFloat() method.

     

To convert a value to a number in JavaScript using parseFloat()

On executing the above code, the following output is generated.

Example 4

The following is an example program to convert a value to a number using unary operator(+).

     

To convert a value to a number in JavaScript using Unary operator

On executing the above code, the following output is generated.

Источник

Оцените статью