17

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;
0

4 Answers 4

28

For integers, 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)

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?

Sign up to request clarification or add additional context in comments.

5 Comments

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.
17

There are three ways to do this:

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

or

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

or

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

Choose wisely :)

4 Comments

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 ++
str = new Number(str) returns an object; that should be str = Number(str).
Another option: val = str * 1;
15

You have several options:

  • 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.

    var num = +str;
    
  • The Number function: value = Number(value). Does the same thing as +.

    var num = Number(str);
    
  • The parseInt function, usually with a radix (number base): value = parseInt(value, 10). The downside here is that parseInt converts any number it finds at the beginning of the string but ignores non-digits later in the string, so parseInt("100asdf", 10) is 100, not NaN. As the name implies, parseInt parses only a whole number.

    var num = parseInt(str, 10);
    
  • The parseFloat function: value = parseFloat(value). Allows fractional values, and always works in decimal (never octal or hex). Does the same thing parseInt does with garbage at the end of the string, parseFloat("123.34alksdjf") is 123.34.

    var num = parseFloat(str);
    

So, pick your tool to suit your use case. :-)

1 Comment

This is the better answer as it answers the question and and it does not bring out the "why would you want to" brigade. Just 8 years too late.
5

The best way:

var str = "1";
var num = +str; //simple enough and work with both int and float

You also can:

var str = "1";
var num = Number(str); //without new. work with both int and float

or

var str = "1";
var num = parseInt(str,10); //for integer number
var num = parseFloat(str); //for float number

DON'T:

var str = "1";
var num = new Number(str);  //num will be an object. typeof num == 'object'

Use parseInt only for special case, for example

var str = "ff";
var num = parseInt(str,16); //255

var str = "0xff";
var num = parseInt(str); //255

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.