javascript tutorial - [Solved-5 Solutions] How to perform integer division and get the remainder we javascript ? - javascript - java script - javascript array
Problem:
In JavaScript, how do we get:
- the whole number of times a given integer goes into another?
- the remainder?
Solution 1:
For some number y and some divisor x compute the quotient (quotient) and remainder (remainder) as:
Solution 2:
I'm no expert in bitwise operators, but here's another way to get the whole number:
This seems correct as well:
Solution 3:
We did some speed tests on Firefox.
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.
Note that Math methods have the advantage over bitwise operators that they work with numbers over 231.