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
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s