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