How to perform an integer division, and separately get the remainder, in JavaScript?

943,167

Solution 1

For some number y and some divisor x compute the quotient (quotient) and remainder (remainder) as:

var quotient = Math.floor(y/x);
var remainder = y % x;

Solution 2

I'm no expert in bitwise operators, but here's another way to get the whole number:

var num = ~~(a / b);

This will work properly for negative numbers as well, while Math.floor() will round in the wrong direction.

This seems correct as well:

var num = (a / b) >> 0;

Solution 3

I did some speed tests on Firefox.

-100/3             // -33.33..., 0.3663 millisec
Math.floor(-100/3) // -34,       0.5016 millisec
~~(-100/3)         // -33,       0.3619 millisec
(-100/3>>0)        // -33,       0.3632 millisec
(-100/3|0)         // -33,       0.3856 millisec
(-100-(-100%3))/3  // -33,       0.3591 millisec

/* a=-100, b=3 */
a/b                // -33.33..., 0.4863 millisec
Math.floor(a/b)    // -34,       0.6019 millisec
~~(a/b)            // -33,       0.5148 millisec
(a/b>>0)           // -33,       0.5048 millisec
(a/b|0)            // -33,       0.5078 millisec
(a-(a%b))/b        // -33,       0.6649 millisec

The above is based on 10 million trials for each.

Conclusion: Use (a/b>>0) (or (~~(a/b)) or (a/b|0)) to achieve about 20% gain in efficiency. Also keep in mind that they are all inconsistent with Math.floor, when a/b<0 && a%b!=0.

Solution 4

ES6 introduces the new Math.trunc method. This allows to fix @MarkElliot's answer to make it work for negative numbers too:

var div = Math.trunc(y/x);
var rem = y % x;

Note that Math methods have the advantage over bitwise operators that they work with numbers over 231.

Solution 5

I normally use:

const quotient =  (a - a % b) / b;
const remainder = a % b;

It's probably not the most elegant, but it works.

Share:
943,167
Yarin
Author by

Yarin

Products PDF Buddy - Popular online PDF editor Gems Snappconfig - Smarter Rails app configuration

Updated on December 30, 2021

Comments

  • Yarin
    Yarin over 2 years

    In JavaScript, how do I get:

    1. The whole number of times a given integer goes into another?
    2. The remainder?