1

we can do the following to convert:

var a = "129.13"|0,  // becomes 129

var b = 11.12|0; // becomes 11

var c = "112"|0; // becomes 112

This seem to work but not sure if this is a standard JS feature. Does any one have any idea if this is safe to use for converting strings and decimals to integers ?

sbr
  • 4,735
  • 5
  • 43
  • 49
  • I suppose [***this***](http://stackoverflow.com/q/596467/871050) wasn't complicated enough for you? – Madara's Ghost Oct 02 '12 at 17:52
  • 1
    See the ECMAScript spec for bitwise operators: http://ecma-international.org/ecma-262/5.1/#sec-11.10. Note that the input (and thus the output also) is converted to Int32. – apsillers Oct 02 '12 at 17:53
  • @MadaraUchiha didn't get exactly what you mean, but thanks for the link – sbr Oct 02 '12 at 18:05

1 Answers1

6

Yes, it is standard behavior. Bitwise operators only operate on integers, so they convert whatever number they're give to signed 32 bit integer.

This means that the max range is that of signed 32 bit integer minus 1, which is 2147483647.

(Math.pow(2, 32) / 2 - 1)|0; // 2147483647

(Math.pow(2, 32) / 2)|0; // -2147483648 (wrong result)
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77