How to Perform Integer Division in JavaScript

To perform integer division by first doing “regular division” and then using “Math.floor()”, “Math.trunc()”, or “bitwise operator” to discard the decimal part of the result.

In JavaScript, there is no built-in operator or function precisely for integer division.

Method 1: Using the Math.floor() function

The “Math.floor()” method “rounds down a number to the nearest integer”. To perform integer division using this method, you first perform the regular division and then pass the result to the “Math.floor()” function, which rounds the result down to the nearest integer, effectively discarding the decimal part.

Example

function integerDivision(dividend, divisor) {
   return Math.floor(dividend / divisor);
}

console.log(integerDivision(10, 3));

Output

3

Method 2: Using the Math.trunc() function

The Math.trunc() method “removes the decimal part of a number, leaving only the integer part”. To perform integer division using this method, you first perform the regular division and then pass the result to the Math.trunc() function, which removes the decimal part, resulting in an integer.

Example

function integerDivision(dividend, divisor) {
  return Math.trunc(dividend / divisor);
}
 
console.log(integerDivision(10, 3));

Output

3

Method 3: Using the Bitwise operators

“Bitwise operator” in JavaScript works with 32-bit signed integers. To perform integer division using a bitwise operator, perform the regular division and then use the bitwise OR operator (|) with 0.

This operation effectively removes the decimal part of the result, resulting in an integer.

However, it is important to note that this method has limitations, as it only works correctly with 32-bit signed integers. Large numbers may produce incorrect results, so use this method with caution.

Example

function integerDivision(dividend, divisor) {
  return (dividend / divisor) | 0;
}

console.log(integerDivision(10, 3));

Output

3

That’s all!

Leave a Comment