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 ?

3
  • I suppose this wasn't complicated enough for you? Commented Oct 2, 2012 at 17:52
  • 1
    See the ECMAScript spec for bitwise operators: ecma-international.org/ecma-262/5.1/#sec-11.10. Note that the input (and thus the output also) is converted to Int32. Commented Oct 2, 2012 at 17:53
  • @MadaraUchiha didn't get exactly what you mean, but thanks for the link Commented Oct 2, 2012 at 18:05

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.