wsxxgw
Last Updated: May 30, 2016
·
4.266K
· xander

Converting a string into an integer in JavaScript*

To convert a string into an integer you could obviously use function parseInt.

parseInt('3', 10); // returns 3
parseInt('3.75', 10); // returns 3

However in many cases we could use also negation operator which is a tilde "~".

~~'3'; // returns 3
~~'3.75'; // returns 3

During bitwise operations operands are being converted into 32 bit integers. We can use it to convert a string into a number by negating bits in a string (it will be converted in that moment) and then negating the result.

Bear in mind that the result of such operation will not be the same as the result of using function parseInt. To see the difference you have to convert something that doesn't look like a number in the first place e.g. convert a string which starts with letters.

parseInt('a', 10); // returns NaN
parseInt({}, 10); // returns NaN
parseInt('123abc', 10); // returns 123
parseInt('abc123', 10); // returns NaN


~~'a'; // returns 0
~~{}; // returns 0
~~'123abc'; // returns 0
~~'abc123'; // returns 0

Also keep in mind that the 32 bit integer is a number in a range from −2 147 483 648 to +2 147 483 647 . That means that when that range will be exceeded then that number will not be automatically converted into something with wider range.

parseInt('1387037027228', 10); // returns 1387037027228
~~'1387037027228'; // returns -237409380

If you have any comments or you're unhappy about my English - please write bellow :)

*Note that the final result of that operation will be not integer since there is no such type in JS - the result will be an instance of Number

11 Responses
Add your response

11543

Simpler way:

> str = '173234786123874612'
'173234786123874612'
> +str
173234786123874620
over 1 year ago ·
11544

@hauleth - it really is simple however it doesn't convert a string to an integer but to a floating-point number:

str = '3.75';
+str; // returns 3.75
over 1 year ago ·
11545

@xander there are no "integers" in JS. IMHO in most cases you shouldn't bother yourself about that one is floating-point or integer. If you need to be sure that this is integer then use Math.floor, Math.ceil or Math.round. No matter if you expect Number or String.

over 1 year ago ·
11548

@hauleth - yeah, I know it's a Number after all. The point of that tip was to show the different ways of solving single problem and using bitwise operations is just a fast way: http://jsperf.com/math-floor-vs-math-round-vs-parseint/33

I also wanted to point the differences between those methods so readers can be aware of those and avoid surprises in the future.

But thanks to you I have learned something new today - thank's for that ;]

over 1 year ago ·
11555

@hauleth I did not know that all numbers in JS are float! Thank you, that is very interesting. Is that because JS in an interpreted language?

over 1 year ago ·
11558

@jailbot - all numbers in JavaSript are instances of Number.
Also NaN (not-a-number) is an instance of a Number.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

Edit
One note here:
If you type e.g.
x = 3;
x won't be an instance of Number. It won't be an object at all. But if you try do deal with it as with a Number

x.toString();

x will be converted to Number on the fly.

over 1 year ago ·
11561

@jailbot it's to simplify implementation of weak typing. If JavaScript used Integers it will add another layer of abstraction to Number. Other interpreted languages have difference between Int and Floats (like Ruby, Python or Smalltalk) but changes between types can be fluid (like / in Python or Smalltalk, first return Float, second Fraction).

over 1 year ago ·
11574

Thanks guys :D

over 1 year ago ·
11817

@jailbot, nothing to do with interpreted vs not. It is just how JavaScript is defined in its language spec. Also, generally there can be different implementations of a language that might be compiled, interpreted, use a bytecode on a VM, etc.

In fact in Chrome (not sure what Firefox/IE do) whenever a JavaScript function is first run it is actually just-in-time compiled to assembly code along with some profiling code. If the function is run enough times it will use that info to recompile the function as more optimized assembly with "optimistic" assertions. It even does things like inlining methods. JavaScript is very dynamic but not necessarily interpreted at all.

over 1 year ago ·
11818

@xander, perhaps it'd be better to put the note about JS not having integers at the top instead of the bottom? Or put an asterisk after "an integer" on the first line? Seems like it is easy to miss in the current spot.

over 1 year ago ·
12120

The idiomatic way to do this without parseInt is to use |0. This is also the approach adopted by the asm.js spec. The effect is the same as ~~. For example, '1387037027228'|0 === -237409380.

The ~ operator is called bitwise not. ~123 === -124 as this is two's complement arithmetic. The sign does change, but that's not the only thing that changes. The unary - operator performs negation. http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.8

over 1 year ago ·