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:
var quotient = Math.floor(y/x);
var remainder = y % x;
click below button to copy the code. By JavaScript tutorial team
Solution 2:
I'm no expert in bitwise operators, but here's another way to get the whole number:
var num = ~~(a / b);
click below button to copy the code. By JavaScript tutorial team
This seems correct as well:
var num = (a / b) >> 0;
click below button to copy the code. By JavaScript tutorial team
Solution 3:
We 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
click below button to copy the code. By JavaScript tutorial team
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.
var div = Math.trunc(y/x);
var rem = y % x;
click below button to copy the code. By JavaScript tutorial team
Note that Math methods have the advantage over bitwise operators that they work with numbers over 231.
Solution 5:
var remainder = x % y;
return (x - remainder) / y;