How can we make numeric out of this line - "2"?

  • @Visman oh? the difference between clearly named functions and, in general, the ways of translating from line to number are two different things - Alexey Shimansky
  • one
    @ Alexey Shimansky, choose your own original question. They are there for several pages, if not mistaken. - Visman
  • @ unicorn23 why is it a duplicate if it is not a duplicate? - Alexey Shimansky
  • one
    @Visman did not see several pages. or you gave the wrong link - Alexey Shimanskiy

5 answers 5

If I understand correctly, and you need to get a number from a string, then use parseInt () for this:

 var str = '2'; console.log(str + 2); str = parseInt(str); console.log(str + 2); 

  • 3
    I liked everyone, but I won't like you, because I don't like you: D I took most of my questions :) - Yuri
  • @Yuri your questions? - Cheg
  • Well, just want to answer the question, but here you have already written. And at the same time you write the same ideas that I wanted to offer :) - Yuri

There is another option to use double bitwise NOT

 var num = '2'; console.log(typeof ~~num); 

  • 3
    with bit operations, you need to be careful, since they only work with int32: ~~'4294967296' === 0 - Grundy
  • the fastest way to multiply by 1 ( str * 1 )

 var str = '2.2'; console.log((str * 1) + 2); 

  • by analogy above: division by 1 or subtraction 0

 var str = '2.2'; console.log((str / 1) + 2); console.log((str - 0) + 2); 

  • add a plus in front of the line ( +str )

 var str = '2.2'; console.log((+str) + 2); 

  • for integer and fractional using Number

 var str = '2.2'; console.log(Number(str) + 2); 

  • option through round only for integer

 var str = '2'; console.log(Math.round(str) + 2); 

  • parseInt (for integers) and parseFloat (for fractional)

For parseInt sometimes necessary to specify the number system.

 var strFloat = '2.2'; var strInt = '2'; console.log(parseFloat(strFloat) + 2); console.log(parseInt(strInt, 10) + 2); 

If you do not specify the number system, it can be like this:

 var result = parseInt("010", 10) == 10; // Returns true var result = parseInt("010") == 10; // Returns false 

But everywhere you have to be careful. If the string contains not only numbers, but other characters as well, then this may not work. For example, as written here: Difference ParseInt, ParseFloat and Number

  • According to MDN, parseFloat has only one argument and the number system is always 10 - andreymal
  • @andreymal so sure. corrected - Alexey Shimansky
  • one
    where the woods about the fastest ? :) - Grundy

There is another option to write the + sign before the string with numbers.

 var str = '2'; console.log(str + 2); console.log(+str + 2); 

    You can still do this using dynamic typing of the JavaScript language.

      var x = "2" console.log(typeof x) x=x*1 console.log(typeof x) 

    after this operation, x will be a number

    • Yes, yes. ANY attempt to make any kind of thing - rst256