There are several ways to divide by a number without a remainder in JS.
Method 1. Rounding:
var x = 10, y = 3.3333;
alert (Math.floor (x / y));
This method is designed for a calculation result greater than zero. If the result is negative, then such a construction will not work correctly.
For example:
Math.floor (-100/3); // Will return -34, although the integer part of -33.33333336 will be -33
Alternatively, to solve this problem by rounding, you can use the if operator:
if (x / y & gt; = 0)
alert (Math.floor (x / y));
else
alert (Math.ceil (x / y));
Method 2:
Probably not as fast as the previous one, but more versatile. Casting to int:
var x = 10, y = 3.3333;
alert (parseInt (x / y));
Method 3 . Productive and versatile:
var x = 10, y = 3.3333;
function div (val, by) {
return (val - val% by) / by;
}
alert (div (x, y));
Well, a little bit of hadcore:
alert (~~ (x / y)) // abbreviated Math.floor () the results will be the same
alert (x / y & gt; & gt; 0)
alert (x / y | 0)
demo at jsfiddle
Answer 1, authority 100%
There is no integer or floating point division in javascript.
As a consequence, it is possible that there are no special arithmetic operators for integers.
Based on this, there are several solutions:
-
Performing regular division and taking an integer part from the result. There are functions for this procedure Math.floor and Math.ceil , the difference is whether a larger integer or a smaller one will be selected.
console.log (Math.floor (10/3)); console.log (Math.floor (-10 / 3)); console.log (Math.ceil (10/3)); console.log (Math.ceil (-10 / 3));
Answer 2, authority 33%
-
As a variant of division, use this construction
function divme (a, b) { return (a - a% b) / b }
-
no
UPD: met another variant of division. Perhaps it will be useful to you. Link
Answer 3, authority 33%
Here’s another option:
Math.floor (a / b);
And like this, but it’s better to be careful with it – it works only for small numbers (somewhere up to 4e9):
a / b | 0
Answer 4, authority 33%
It all depends on how you want to round off the division.
Math.floor (a / b); Math.floor (3/2); // = 1
Math.ceil (a / b); Math.ceil (3/2); // = 2;
Answer 5, authority 33%
Use the Math.trunc (x) function;
Math.trunc (13.37); // 13 Math.trunc (42.84); // 42 Math.trunc (0.123); // 0 Math.trunc (-0.123); // -0 Math.trunc ('- 1.123'); // -1
-