How to perform integer division and get the remainder in JavaScript
In JavaScript, how can I:
- Calculate the whole number quotient when dividing one integer by another?
- Obtain the remainder from the division operation?
What are the built-in operators or methods available for these operations, and how do they work with different types of numbers?
In JavaScript, you can perform integer division using Math.floor() or Math.trunc() functions to get the whole number quotient, and obtain the remainder using the % operator. For integer division, Math.floor() rounds down while Math.trunc() simply removes the decimal part, with different behaviors for negative numbers. The remainder operator % returns the remainder left over when one operand is divided by another, always taking the sign of the dividend.
Contents
- Integer Division Methods
- Remainder and Modulo Operations
- Handling Negative Numbers
- Performance Considerations
- Practical Examples
Integer Division Methods
JavaScript doesn’t have a built-in integer division operator like some other languages, so you need to use specific methods to obtain the whole number quotient. Here are the main approaches:
Math.floor() for Integer Division
Math.floor() always rounds down to the nearest integer, making it suitable for positive numbers:
const quotient = Math.floor(7 / 3); // Returns 2
const quotient2 = Math.floor(10 / 3); // Returns 3
According to the MDN documentation, Math.floor() returns the largest integer less than or equal to the given number.
Math.trunc() for Integer Division
Math.trunc() simply removes the decimal part without rounding:
const quotient = Math.trunc(7 / 3); // Returns 2
const quotient2 = Math.trunc(10 / 3); // Returns 3
As explained by GoLinuxCloud, “the trunc method simply returns the integer part of a number and removes any fractional digits that are present within a Number value.”
Bitwise Operators
For small numbers, you can use bitwise operators which offer better performance:
const quotient = ~~(7 / 3); // Returns 2
const quotient2 = ~~(10 / 3); // Returns 3
The Delft Stack article notes that “the performance of bitwise operators is greater than the Math library functions, but the capacity to handle large numbers is less. So, if you have small numbers, you can use the bitwise operators; otherwise, use the Math library functions.”
Remainder and Modulo Operations
The Remainder Operator (%)
JavaScript provides the % operator to get the remainder from a division operation:
const remainder = 7 % 3; // Returns 1
const remainder2 = 10 % 3; // Returns 1
According to the MDN documentation on remainder operator, “The remainder (%) operator returns the remainder left over when one operand is divided by a second operand.”
Calculating Both Quotient and Remainder
You can calculate both the integer division and remainder in one operation:
const dividend = 13;
const divisor = 5;
const quotient = Math.floor(dividend / divisor); // 2
const remainder = dividend % divisor; // 3
The wikitechy article suggests an alternative approach: var remainder = x % y; return (x - remainder) / y;
Handling Negative Numbers
Different Behaviors with Negative Numbers
The various integer division methods behave differently when dealing with negative numbers:
// Math.floor() behavior
console.log(Math.floor(-7 / 3)); // Returns -3 (rounds down)
// Math.trunc() behavior
console.log(Math.trunc(-7 / 3)); // Returns -2 (removes decimal)
// Bitwise operator behavior
console.log(~~(-7 / 3)); // Returns -2
As Codemia explains, “if dealing with negative numbers, you might want to use Math.trunc() which simply trims off the decimal without rounding.”
Remainder Operator with Negative Numbers
The remainder operator % takes the sign of the dividend:
console.log(7 % 3); // Returns 1
console.log(-7 % 3); // Returns -1 (sign of dividend)
console.log(7 % -3); // Returns 1 (sign of dividend)
console.log(-7 % -3); // Returns -1 (sign of dividend)
The GeeksforGeeks article states that “The JavaScript %(modulo) behaves like a remainder operation and gives the remainder and as the number is negative therefore remainder also comes out to be negative.”
True Modulo vs Remainder
JavaScript’s % operator is technically a remainder operator, not a true modulo operator. A true modulo always returns a positive result:
// True modulo calculation
function trueModulo(dividend, divisor) {
const remainder = dividend % divisor;
return remainder >= 0 ? remainder : remainder + divisor;
}
console.log(trueModulo(-7, 3)); // Returns 2 (true modulo)
console.log(-7 % 3); // Returns -1 (remainder)
As 2ality.com explains, “If both dividend and divisor are positive, the modulo operator produces the same results as the remainder operator. If, however, dividend and divisor have different signs, then the results are different.”
Performance Considerations
Bitwise Operators Performance
Bitwise operators like ~~ offer better performance for small numbers:
// Performance test
console.time('Math.floor');
for (let i = 0; i < 1000000; i++) Math.floor(i / 3);
console.timeEnd('Math.floor');
console.time('Bitwise');
for (let i = 0; i < 1000000; i++) ~~(i / 3);
console.timeEnd('Bitwise');
However, as noted earlier, bitwise operators have limitations with large numbers. The Delft Stack article warns that “if you have small numbers, you can use the bitwise operators; otherwise, use the Math library functions like the math.floor function and the math.trunc function.”
Math.trunc() vs Math.floor()
Math.trunc() is generally preferred over Math.floor() for integer division because:
- It works consistently for both positive and negative numbers when you want to simply remove the decimal part
- It doesn’t introduce the rounding behavior that might be unexpected
- It was introduced in ES6, making it the more modern approach
Practical Examples
Basic Integer Division Example
function integerDivision(dividend, divisor) {
if (divisor === 0) throw new Error('Division by zero');
return Math.trunc(dividend / divisor);
}
console.log(integerDivision(13, 5)); // 2
console.log(integerDivision(-13, 5)); // -2
console.log(integerDivision(13, -5)); // -2
Complete Division Function
function divide(dividend, divisor) {
if (divisor === 0) throw new Error('Division by zero');
const quotient = Math.trunc(dividend / divisor);
const remainder = dividend % divisor;
return {
quotient,
remainder,
trueModulo: remainder >= 0 ? remainder : remainder + divisor
};
}
console.log(divide(13, 5));
// { quotient: 2, remainder: 3, trueModulo: 3 }
console.log(divide(-13, 5));
// { quotient: -2, remainder: -3, trueModulo: 2 }
Array Processing Example
function distributeItems(totalItems, people) {
if (people <= 0) throw new Error('Number of people must be positive');
const itemsPerPerson = Math.floor(totalItems / people);
const remainderItems = totalItems % people;
return {
itemsPerPerson,
remainderItems,
distribution: Array(people).fill(itemsPerPerson).map((items, index) =>
index < remainderItems ? items + 1 : items
)
};
}
console.log(distributeItems(10, 3));
// {
// itemsPerPerson: 3,
// remainderItems: 1,
// distribution: [4, 3, 3]
// }
Conclusion
Key Takeaways
-
Integer Division: Use
Math.trunc()for consistent behavior with both positive and negative numbers, orMath.floor()if you specifically need rounding down behavior. -
Remainder Operation: The
%operator returns the remainder and takes the sign of the dividend. For true modulo behavior, additional calculations are needed. -
Negative Numbers: Be aware that different methods behave differently with negative numbers -
Math.trunc()removes decimals whileMath.floor()rounds down. -
Performance: Bitwise operators like
~~offer better performance for small numbers but have limitations with large numbers. -
ES6 Features:
Math.trunc()was introduced in ES6 and provides a more consistent approach to integer division.
Practical Recommendations
- For most cases, use
Math.trunc()for integer division as it provides consistent behavior - Use the
%operator for remainder operations - Be mindful of negative number behavior differences between methods
- Use bitwise operators only when performance is critical and you’re working with small numbers
- Implement true modulo logic when you need positive remainders
Related Questions
- What’s the difference between remainder and modulo in JavaScript?
- How do I handle division by zero in JavaScript?
- Which method is faster for integer division in JavaScript?
Sources
- How to perform an integer division, and separately get the remainder, in JavaScript - Stack Overflow
- Division in JavaScript - GeeksforGeeks
- Integer Division and Finding the Remainder in JavaScript - Stackabuse
- Integer Division in JavaScript | Delft Stack
- JavaScript Integer Division [3 Methods] | GoLinuxCloud
- Codemia | How to perform an integer division, and separately get the remainder, in JavaScript
- Integer division in JavaScript explained - DEV Community
- JavaScript Integer Division: Examples and Tips - SkillReactor Blog
- javascript tutorial - How to perform integer division and get the remainder we javascript ? - wikitechy
- Division (/) - JavaScript | MDN
- JavaScript % (modulo) gives a negative result for negative numbers - Stack Overflow
- How to get negative result using modulo operator in JavaScript ? - GeeksforGeeks
- Understanding the JavaScript Modulo Operator - Reddit
- The Modulus Operator in JavaScript - Mastering JS
- JavaScript Remainder(%) Operator - GeeksforGeeks
- How does Javascript handle a negative modulo? (
-5 % 20) - Codecademy Forums - Remainder (%) - JavaScript | MDN
- Remainder operator vs. modulo operator (with JavaScript code) - 2ality.com