javascript - rounding down in js
PHP中文网
PHP中文网 2017-06-26 10:55:11
0
5
888

In js, in the past, the Math.floor method was used to round down, but now we see this usage: OR operation
interval = interval | 0
Why can we round down in this way? , what are the advantages of this usage compared with Math.floor?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all (5)
某草草

Note that|is not a logical OR, but a bitwise OR (OR).

Some small differences. For example,Math.floor(NaN)still returnsNaN. ButNaN | 0returns 0.
Another example isMath.floor(Infinity)returnsInfinity, butInfinity | 0returns 0

    过去多啦不再A梦

    You can also do thisinterval = interval >> 0

      给我你的怀抱
      • First of all, S1ngS1ng upstairs is right about those small differences.

      • In addition,|is a bitwise OR operation. Since when0is stored in the memory, all integer bits are filled with 0, so the OR operation is performed based on the binary bit and a numerical value. Regardless of the corresponding bit Whether0or1is ORed with0, you will get itself. However, since the number 0 does not have a decimal part in the memory, the decimal part ofintervalis discarded after the bitwise OR operation. In fact, rounding down is achieved by discarding the decimal part.

      • Since it is a bit operation, it will be faster thanMath.floor().

        三叔

        The real reason is: automatic type conversion within js.

        js values are all expressed in64-bitfloating point type. When a value requiresbit operations, js will automatically convert it into a32-bit signedinteger and discard the decimal part.

        n|0; n>>0; //The following 0 is only used to ensure that the integer value of n remains unchanged.

        Reducing from 64-bit to 32-bit will cause a loss of accuracy.Be careful!, maximum effective range: 2^32/2-1

        > f64=(Math.pow( 2,32)/2-1)-0.5 2147483646.5 > f64|0 2147483646 > f64>>0 2147483646 > (f64 + 2)|0 //超出有效范围 -2147483648 > (f64 + 2)>>0 //超出有效范围 -2147483648 > Math.floor(f64 + 2) //正确 2147483648
          给我你的怀抱

          Both can be achieved,interval = interval | 0This is a writing technique, it depends on personal preference. It may be thatinterval = interval | 0will run faster, and writing code will definitely be faster thanMath.floor!

            Latest Downloads
            More>
            Web Effects
            Website Source Code
            Website Materials
            Front End Template
            About us Disclaimer Sitemap
            php.cn:Public welfare online PHP training,Help PHP learners grow quickly!