2

Converting floating number into integer We can use ( number | 0 ) statement instead of parseInt(number) in Javascript. for example : ( 3.343 | 0) gives an integer value 3. Please Explain what is the logic behind ( number | 0 ) statement.

Mosè Raguzzini
  • 12,776
  • 26
  • 36
  • I'ts a way in javascript of making a number into a integer. The Javascript Engine can then do certain optmizations,.. eg. Integer muliply / add etc, instead of double. – Keith Aug 31 '17 at 22:33
  • Are you asking how `number | 0` works or why `number | 0` is used rather than `parseInt`? – Sebastian Simon Aug 31 '17 at 22:38
  • 1
    No, you should not use this instead of a proper `parseInt`. – Bergi Sep 01 '17 at 00:34

2 Answers2

1

The | operator performs bitwise logical OR. It requires its parameters to be integers, so it will convert a string to an integer. So

( number | 0 )

is equivalent to:

( parseInt(number, 10) | 0 )

Any number or'ed with 0 will return that same number, so that makes it equivalen to:

parseInt(number, 10)
Barmar
  • 596,455
  • 48
  • 393
  • 495
  • I think there might be some confusion from the OP about type coercion here too. In the case described above, the confusion is how `"123" | 0 = 123`. – AJ X. Aug 31 '17 at 22:41
  • No, those are not equivalent. Try with the input `number = "0xFF"`. Or `1e11`. Or `0b11`. Or `Infinity`. – Bergi Sep 01 '17 at 00:35
0

Well, the single pipe between the number and 0 is bitwise operator that treat their operands as a sequence of 32 bits (zeroes and ones). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#.7c_%28Bitwise_OR%29

Mobi
  • 46
  • 4