Search code examples
javascriptfloating-pointbitwise-operators

Why does << 0 remove the decimal portion of a number in JavaScript?


When you have a floating-point number, say 10.1, and you utilize the zero fill left shift operator (<<) in JavaScript, it returns just the integer portion of the number, say 10 for the example.

Here's some source code showing what I mean:

var num1 = 958.51243

console.log(num1) // 958.51243
console.log(num1 << 0) // 958		

Why does this happen?


Solution

  • See the docs:

    The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format, except for zero-fill right shift which results in an unsigned 32-bit integer.

    So the numbers will be converted to integers before the operation is performed.

    For left shift, it's described in the official specification here:

    6.1.6.1.9 Number::leftShift ( x, y )

    1. Let lnum be ! ToInt32(x).

    2. Let rnum be ! ToUint32(y).

    3. (...perform operation...)

    Where ToInt32 does:

    The abstract operation ToInt32 converts argument to one of 2^32 integer values in the range -2^31 through 2^31 - 1, inclusive.