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;
4 Answers 4
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?
5 Comments
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
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
str = new Number(str) returns an object; that should be str = Number(str).val = str * 1;You have several options:
The unary
+operator:value = +valuewill 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"is1.5). Any non-digits in the string (other than theefor scientific notation) make the resultNaN. Also,+""is0, which may not be intuitive.var num = +str;The
Numberfunction:value = Number(value). Does the same thing as+.var num = Number(str);The
parseIntfunction, usually with a radix (number base):value = parseInt(value, 10). The downside here is thatparseIntconverts any number it finds at the beginning of the string but ignores non-digits later in the string, soparseInt("100asdf", 10)is100, notNaN. As the name implies,parseIntparses only a whole number.var num = parseInt(str, 10);The
parseFloatfunction:value = parseFloat(value). Allows fractional values, and always works in decimal (never octal or hex). Does the same thingparseIntdoes with garbage at the end of the string,parseFloat("123.34alksdjf")is123.34.var num = parseFloat(str);
So, pick your tool to suit your use case. :-)
1 Comment
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