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.
2 Answers
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)
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
number | 0works or whynumber | 0is used rather thanparseInt?parseInt.