JavaScript – Division get whole numbers using bitwise operators

Posted on

When you divide 9/5 in JavaScript you get 1.8, which is a fractional number. What if we only wanted a remainder-less whole number quotient, C integer style?

printf("%i",7/5);  /* C prints 1 */

Most often, you will see people use Math.floor

console.log(Math.floor(7/5)) // prints 1

Another method you can use is to use the bitwise NOT operator ~ to do the same thing

console.log(~~(7/5)) //prints 1

Leave a comment