views:

97

answers:

2

Is there any way to convert a variable from string to number?

For example, I have

var str = "1";

Can I change it to

var str = 1;
+6  A: 

Try str = parseInt( str, 10 )

(note: the second parameter signifies the radix for parsing; in this case, your number will be parsed as a decimal)

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?

Fyodor Soikin
Always include the radix.
Sean Kinsey
@Sean: Thanks, corrected.
Fyodor Soikin
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.
Warrantica
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.
Sean Kinsey
@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"?
Fyodor Soikin
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.
Warrantica
@Fyodor OK, question edited ;)
Warrantica
+5  A: 

There are three ways to do this:

str = parseInt(str, 10); // 10 as the radix sets parseInt to expect decimals

or

str = new Number(str); // this does not support octals

or

str = +str; // the + operator causes the parser to convert using Number

Choose wisely :)

Sean Kinsey
My previous question was in error. http://bclary.com/2004/11/07/#a-11.4.6 The + operator doesn't do what it does in other languages (foo > 0 ? foo : -foo;)
Conspicuous Compiler
@Consp... I'm not following you, whats the relevance? But for your sample code you need to use -- or ++
Sean Kinsey
Why was my answer down-voted?
Sean Kinsey