Last Updated: May 07, 2016
·
281
· TheIronDeveloper

Bitwise OR to drop decimals

var test = 5.5;
0|test; // 5

I've seen using the ~ bitwise operation to drop decimals from a number. The reason it works is because using bitwise operations convert a number to a signed 32-bit integer. Using the bitwise NOT ~ twice will do the following:

  • convert the current number to a signed integer.
  • performs the NOT operation, which converts all the 0 bits to 1s, and 1s to 0.
  • performs the NOT operation (again), returning the number to its earlier state.

While thats cool and all, using the bitwise OR operation 0| compares two numbers and makes a new number where either bit is a 1. So doing 0|test does the following:

  • converts test to a signed integer
  • performs the OR operation, which will:
    • check for the 1s in the 0 (which, there are none)
    • check for the 1s in test
  • Returns the signed integer version of test (since 0 has 0 1s)

I haven't done any perf tests on this... but fundamentally it feels better to do this than to flip and unflip all the 1s and 0s.

Some bitops docs here


With all that said, please don't do this. :) Its super unreadable, and you have the possibility of losing information if the number is larger than 2^32.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside