Javascript: convert string to number?

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

For example, I have

var str = "1"; 

Is it possible to change it to

 var str = 1; 
+2
source share
4 answers

Try str = parseInt( str, 10 )

(note: the second parameter denotes the radius for parsing, in which case your number will be parsed as decimal)

However, however, the term β€œtype” is used fairly loosely in JavaScript. Could you explain why you relate to the type of a variable in general?

+9
source

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 :)

+8
source

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 

DO NOT:

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

Use parseInt only for a special case, for example

 var str = "ff"; var num = parseInt(str,16); //255 var str = "0xff"; var num = parseInt(str); //255 
+2
source

You have several options:

  • The unary + : value = +value operator will force a string to a number using standard JavaScript rules. The number may have a fractional part (for example, +"1.50" is 1.5 ). Any non-digits in the string (except e for scientific notation) make the result NaN . In addition, +"" is 0 , which may be unintuitive.

     var num = +str; 
  • Function Number : value = Number(value) . Same as + .

     var num = Number(str); 
  • The parseInt function, usually with a radius (numeric base): value = parseInt(value, 10) . The disadvantage here is that parseInt converts any number that it finds at the beginning of the line, but ignores the non-digital parseInt("100asdf", 10) later in the line, so parseInt("100asdf", 10) is 100 , not NaN . As the name suggests, parseInt parses only an integer.

     var num = parseInt(str, 10); 
  • Function parseFloat : value = parseFloat(value) . Allows fractional values ​​and always works in decimal (never octal or hexadecimal). The same thing does parseInt with garbage at the end of the line, parseFloat("123.34alksdjf") - 123.34 .

     var num = parseFloat(str); 

So, choose your tool according to your use case. :-)

+1
source

Source: https://habr.com/ru/post/1012469/


All Articles