5

Is there any trick to convert string to integer in javascript without using any function and methods?

var s = "5"
console.log(typeof(s)) // out put is string 
console.log(typeof(parseInt(s))) // i want out put which is number with out using parseInt() or other functions for optimizing code.

Any help would be appreciated. Thanks in advance.

Wasif Ali
  • 880
  • 1
  • 12
  • 28
code7004
  • 120
  • 1
  • 7
  • my question is different first read full question i know this type of question was asked before – code7004 Feb 28 '19 at 07:17
  • 1
    Possible duplicate: https://stackoverflow.com/questions/1133770/convert-a-string-to-an-integer-in-javascript. – Rajesh Feb 28 '19 at 07:21
  • there is an oneother answer with using (-) which cast string in to integer – manan5439 Feb 28 '19 at 07:26
  • 1
    @Rajesh Please don't stuck to the example code, the question says "_convert string to integer_" Any string ... – Teemu Feb 28 '19 at 07:27
  • 1
    @Teemu So for `s="5.5"`, expected output should be `5` and not `5.5` as `+s` returns... Damn! I didn't think of this – Rajesh Feb 28 '19 at 07:30

3 Answers3

6

You can cast the string to number using unary plus (+). This will do nothing much beside some code optimization.

var s = "5"
s = +s;
console.log(typeof(s), s);

var s = "5.5"
s = +s;
console.log(typeof(s), s);
Takit Isy
  • 8,976
  • 3
  • 19
  • 46
Mamun
  • 62,450
  • 9
  • 45
  • 52
  • `var s = "5.5"` What now? – Teemu Feb 28 '19 at 07:21
  • 1
    @TakitIsy Exactly, and that's not what was asked ("_convert string to __integer___"). It doesn't matter, though, since OP has accepted an answer which doesn't do what they actually asked for ... – Teemu Mar 04 '19 at 13:47
  • @Teemu I agree, but well… I guess the OP meant *number* and not *integer* anyway. For many, *integers* are just *numbers*. – Takit Isy Mar 04 '19 at 14:57
5

here is a most effective way to convert string into int without using any built in function have a look at code. Thank you:)

var s = "5"
var i = s - 0
console.log(typeof(i)) // you will get a number without using any built in function... because (-) will cast string in to number
manan5439
  • 858
  • 8
  • 24
3

You can try using bit-wise operator s|0. This will convert value to integer. However, this will also convert floating values to integer.

var s = "5"
var y = s|0;
console.log(typeof(y), s, y);

var s = "5.5"
var y = s|0;
console.log(typeof(y), s, y);
Rajesh
  • 22,581
  • 5
  • 41
  • 70