Search code examples
javascriptbit-shift

Why this code works fine(Im trying to get integer part of numbers)?


So actually i know the solution of this problem, but i cant understand how its working. The following function get whole part of decimal value. Who can explain me, how its works?

function getDecimal(num) {
    num = num << 1;
    num = num >> 1;
    return num;
}

console.log(getDecimal(123));


Solution

  • This function doesn't actually work for what you're trying to do. These examples will break it:

    getDecimal(123.3) // returns 122
    getDecimal(123) // returns 122
    

    The way bitwise operators work in javascript is that they convert the number to an integer, do some processing, then convert it back to a javascript number. Effectively, your function does the following:

    1. Takes input number (123.2) and converts it to an int - 123
    2. Bit shift the number by 1 bit (remove last bit) - 61
    3. Bit shift the number by 1 bit the other way (add a zero to the end) - 122
    4. Returns this value (122)

    This is not the correct way of getting the integer part of a floating point number. Use Math.ceil(num) instead.