In JavaScript, how do I get:
- The whole number of times a given integer goes into another?
- The remainder?
In JavaScript, how do I get:
For some number y
and some divisor x
compute the quotient (quotient
)[1] and remainder (remainder
) as:
const quotient = Math.floor(y/x);
const remainder = y % x;
Example:
const quotient = Math.floor(13/3); // => 4 => the times 3 fits into 13
const remainder = 13 % 3; // => 1
[1] The integer number resulting from the division of one number by another
floor
and %
together is not consistent in that way. Either use trunc
instead of floor
(thereby permitting negative remainders) or use subtraction to get the remainder (rem = y - div * x
). –
Cooky Math.floor()
here is just for the case that given number are positive. look at this for more explaination. Normally parseInt()
is a better choose to get integer part of number or string. –
Tullus rem
anyway, you can get the quotient div
faster without flooring: (y - rem) / x
. 2. By the way the modulo operation by Donald Knuth's recommended definition (sign-matches-divisor, not the remainder i.e. Euclidean modulus, nor the JavaScript sign-matches-dividend) is what we can code in JavaScript as function mod (a, n) { return a % n + (Math.sign(a) !== Math.sign(n) ? n : 0); }
. –
Warner quotient * divisor + remainder = dividend
true, the quotient has to be the floor. –
Cooky -9 % 2
is -1
instead of 1
. –
Mideast 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;
Note: Only use ~~
as a substitution for Math.trunc()
when you are confident that the range of input falls within the range of 32-bit integers.
a/b | 0
–
Pomfrey ~~int
, int | 0
and int >> 0
doesn't modify initial argument, but make interpreter pass integral part to operator. –
Katydid floor
hardly rounds in the wrong direction, given its name - just not the direction that people generally want though! –
Citadel a = 12447132275286670000; b = 128
Math.floor(a/b)
-> 97243220900677100
and ~~(a/b)
-> -1231452688
. –
Swam ~~(5/2) --> 2
as does (5/2)>>0 --> 2
, but ~~(5/2) + 1 --> 3
, while ~~(5/2)>>0 + 1 --> 1
. ~~
is a good choice because the precedence is more appropriate. –
Invigorate >>0
is why emscripten and asm.js use |0
–
Afterdeck Math.floor
when numbers go beyond 53 bits... It's just the inherent limitations present all over the place. If you want to do this for arbitrarily large numbers, you need some bigint / bignumber library. –
Dunning Math.floor
rounds the negative quotient in the wrong, but rather in a different direction. Math.floor(-3 / 10) === -1
would then correspond to floored division (rounds "downwards"), whereas ~~(-3 / 10) === 0
corresponds to truncated division (rounds "towards zero"). See Wiki: Modulo operation. –
Bocanegra Math.floor
or the new Math.trunc
of ES6 (Edge 12+) –
Fosse | 0
to truncate, particularly due to its use in asm.js, so you can't exactly say it obfuscates the code, because its meaning is already widely known. –
Matthewmatthews |0
. Also it's irrelevant that asm.js uses a specific style since it's not meant to be written/read by humans but by transpilers and browsers –
Fosse ~~
or | 0
didn't already helpfully exist, someone might've been tempted to add them. As Joel has said, "Old code doesn’t rust". Don't not use helpful existing conventions simply because they're old. This is A Good One. –
Ancel TypeError: unsupported operand type(s) for |: 'float' and 'int'
–
Moller Math.trunc()
is recommended. As the docs point out using bitwise no-ops to truncate will produce bugs when used with values that don't fit within the range of 32-bits. –
Lungki 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
.
Math.floor
and the who-knows-how-many other API functions, or learning about the ~
(bitwise-not) operator and how bitwise operations work in JS and then understanding the effect of double tilde? –
Dunning Math.floor
better. And even if not, this one is googleable. –
Laity |0
is doing, since it looks like a non-op… “Yep—it's a cast-to-int” being a clear and direct answer leads me to be a fan of this choice –
Densimeter TypeError: unsupported operand type(s) for |: 'float' and 'int'
–
Moller Math.floor(a/b)
to a bitwise operation seems simple enough. –
Pfaff 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.
18014398509481984 == 18014398509481985
. –
Navigator 18014398509481984 / 5
is 3602879701896396.8
. However, that can't be stored, so it is converted to 3602879701896397
. And then Math.trunc(3602879701896397)
is 3602879701896397
. –
Navigator ~~(x/y)
. Need to support bigger numbers up to 54 bits signed? Use Math.trunc
if you have it, or Math.floor
otherwise (correct for negative numbers). Need to support even bigger numbers? Use some big number library. –
Dunning divmod
, you can implement it as such: function divmod(x, y) { var div = Math.trunc(x/y); var rem = x % y; return [div, rem]; }
–
Saccharometer I normally use:
const quotient = (a - a % b) / b;
const remainder = a % b;
It's probably not the most elegant, but it works.
var remainder = x % y;
return (x - remainder) / y;
Math.trunc
:). I checked with 100,3; -100,3; 100,-3 and -100,-3. Of course, a lot of time has passed since your comment and things change. –
Excrescent You can use the function parseInt
to get a truncated result.
parseInt(a/b)
To get a remainder, use mod operator:
a%b
parseInt have some pitfalls with strings, to avoid use radix parameter with base 10
parseInt("09", 10)
In some cases the string representation of the number can be a scientific notation, in this case, parseInt will produce a wrong result.
parseInt(100000000000000000000000000000000, 10) // 1e+32
This call will produce 1 as result.
parseInt
should be avoided when possible. Here is Douglas Crockford's warning: "If the first character of the string is 0, then the string is evaluated in base 8 instead of base 10. In base 8, 8 and 9 are not digits, so parseInt("08") and parseInt("09") produce 0 as their result. This error causes problems in programs that parse dates and times. Fortunately, parseInt can take a radix parameter, so that parseInt("08", 10) produces 8. I recommend that you always provide the radix parameter." archive.oreilly.com/pub/a/javascript/excerpts/… –
Adali parseInt
should be avoided; just that there are some gotchas to be aware of. You must be aware of these things and be prepared to cope. –
Precise parseInt
with a number argument. parseInt
is supposed to parse partially-numerical strings, not truncate numbers. –
Navigator Math.floor(operation)
returns the rounded down value of the operation.
Example of 1st question:
const x = 5;
const y = 10.4;
const z = Math.floor(x + y);
console.log(z);
Example of 2nd question:
const x = 14;
const y = 5;
const z = Math.floor(x % y);
console.log(x);
JavaScript calculates right the floor of negative numbers and the remainder of non-integer numbers, following the mathematical definitions for them.
FLOOR is defined as "the largest integer number smaller than the parameter", thus:
REMAINDER is defined as the "left over" of a division (Euclidean arithmetic). When the dividend is not an integer, the quotient is usually also not an integer, i.e., there is no remainder, but if the quotient is forced to be an integer (and that's what happens when someone tries to get the remainder or modulus of a floating-point number), there will be a non-integer "left over", obviously.
JavaScript does calculate everything as expected, so the programmer must be careful to ask the proper questions (and people should be careful to answer what is asked!) Yarin's first question was NOT "what is the integer division of X by Y", but, instead, "the WHOLE number of times a given integer GOES INTO another". For positive numbers, the answer is the same for both, but not for negative numbers, because the integer division (dividend by divisor) will be -1 smaller than the times a number (divisor) "goes into" another (dividend). In other words, FLOOR will return the correct answer for an integer division of a negative number, but Yarin didn't ask that!
gammax answered correctly, that code works as asked by Yarin. On the other hand, Samuel is wrong, he didn't do the maths, I guess, or he would have seen that it does work (also, he didn't say what was the divisor of his example, but I hope it was 3):
Remainder = X % Y = -100 % 3 = -1
GoesInto = (X - Remainder) / Y = (-100 - -1) / 3 = -99 / 3 = -33
By the way, I tested the code on Firefox 27.0.1, it worked as expected, with positive and negative numbers and also with non-integer values, both for dividend and divisor. Example:
-100.34 / 3.57: GoesInto = -28, Remainder = -0.3800000000000079
Yes, I noticed, there is a precision problem there, but I didn't had time to check it (I don't know if it's a problem with Firefox, Windows 7 or with my CPU's FPU). For Yarin's question, though, which only involves integers, the gammax's code works perfectly.
Use:
const idivmod = (a, b) => [a/b |0, a%b];
There is also a proposal working on it: Modulus and Additional Integer Math
Alex Moore-Niemi's comment as an answer:
For Rubyists here from Google in search of divmod
, you can implement it as such:
function divmod(x, y) {
var div = Math.trunc(x/y);
var rem = x % y;
return [div, rem];
}
Result:
// [2, 33]
divmod
uses floored division (Math.floor
), which differs from truncated division (Math.trunc
) when negative numbers are involved. This is the case for NPM divmod
package, Ruby divmod
, SWI-Prolog divmod
and probably many other implementations, too. –
Valerle divmod
exists because it is performs twice as fast as computing the two operations separately. Providing such a function without this performance benefit might be confusing. –
Valerle There are several possible definitions for the primitive functions div
(which computes the quotient of a division) and mod
(which computes the remainder of a division) that satisfy these constraints:
Number.isInteger(div(x, y))
;x === div(x, y) * y + mod(x, y)
;Math.abs((mod(x, y)) < Math.abs(y)
.The definitions that are in common usage in the computer science literature and in programming languages are based on
the truncated division:
function div(x, y) {
return Math.trunc(x / y);
}
function mod(x, y) {
return x % y;
}
the floored division:
function div(x, y) {
return Math.floor(x / y);
}
function mod(x, y) {
return ((x % y) + y) % y;
}
the Euclidean division:
function div(x, y) {
return Math.sign(y) * Math.floor(x / Math.abs(y));
}
function mod(x, y) {
const z = Math.abs(y);
return ((x % z) + z) % z;
}
Additionally,
mod(x, y) * x >= 0
;mod(x, y) * y >= 0
;mod(x, y) >= 0
.Consequently,
x >= 0
and y > 0
, then the truncated, floored, and Euclidean divisions agree;x >= 0
and y < 0
, then the truncated and Euclidean divisions agree;x <= 0
and y > 0
, then the floored and Euclidean divisions agree;x <= 0
and y < 0
, then the truncated and floored divisions agree.The choice of the Euclidean division is recommended over the truncated and floored divisions for defining the functions div
and mod
, according to the paper ‘The Euclidean definition of the functions div and mod’ by Raymond Boute:
In this paper we clarify the differences between the various definitions, in particular those based on division by truncation (T-definition) and on division by flooring (F-definition) as defined by Knuth. We also propose still another definition, which we call Euclidean because it is based on Euclid’s theorem (E-definition). This alternative is rarely discussed in the literature, yet on closer analysis it is advantageous in terms of regularity and useful mathematical properties, both theoretically and in practical usage. The Euclidean definition usually emerged as the most straightforward choice, over a wide variety of representative application areas where we experienced the need for a div-mod function pair.
we can use the below approach.
quotient = dividend / divisor | 0;
and any way we can get reminder with modulo operator
remainder = dividend % divisor;
If you need to calculate the remainder for very large integers, which the JS runtime cannot represent as such (any integer greater than 2^32 is represented as a float and so it loses precision), you need to do some trick.
This is especially important for checking many case of check digits which are present in many instances of our daily life (bank account numbers, credit cards, ...)
First of all you need your number as a string (otherwise you have already lost precision and the remainder does not make sense).
str = '123456789123456789123456789'
You now need to split your string in smaller parts, small enough so the concatenation of any remainder and a piece of string can fit in 9 digits.
digits = 9 - String(divisor).length
Prepare a regular expression to split the string
splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g')
For instance, if digits
is 7, the regexp is
/.{1,7}(?=(.{7})+$)/g
It matches a nonempty substring of maximum length 7, which is followed ((?=...)
is a positive lookahead) by a number of characters that is multiple of 7. The 'g' is to make the expression run through all string, not stopping at first match.
Now convert each part to integer, and calculate the remainders by reduce
(adding back the previous remainder - or 0 - multiplied by the correct power of 10):
reducer = (rem, piece) => (rem * Math.pow(10, digits) + piece) % divisor
This will work because of the "subtraction" remainder algorithm:
n mod d = (n - kd) mod d
which allows to replace any 'initial part' of the decimal representation of a number with its remainder, without affecting the final remainder.
The final code would look like:
function remainder(num, div) {
const digits = 9 - String(div).length;
const splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g');
const mult = Math.pow(10, digits);
const reducer = (rem, piece) => (rem * mult + piece) % div;
return str.match(splitter).map(Number).reduce(reducer, 0);
}
If you are just dividing with powers of two, you can use bitwise operators:
export function divideBy2(num) {
return [num >> 1, num & 1];
}
export function divideBy4(num) {
return [num >> 2, num & 3];
}
export function divideBy8(num) {
return [num >> 3, num & 7];
}
(The first is the quotient, the second the remainder)
function divideByPowerOf2(num, exponent) { return [num >> exponent, num & ((1 << exponent) - 1)]; }
. –
Valerle Calculating the number of pages may be done in one step:
Math.ceil(x/y)
function integerDivison(dividend, divisor) {
this.Division = dividend/divisor;
this.Quotient = Math.floor(dividend/divisor);
this.Remainder = dividend%divisor;
this.calculate = () => {
return {Value:this.Division, Quotient:this.Quotient, Remainder:this.Remainder};
}
}
var divide = new integerDivison(5, 2);
console.log(divide.Quotient) // To get the quotient of two values
console.log(divide.division) // To get the floating division of two values
console.log(divide.Remainder) // To get the remainder of two values
console.log(divide.calculate()) // To get the object containing all the values
If you need the quotient for some stupidly big numbers, you can use:
Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(Math.abs(x/y))))) * Math.sign(x/y))
NOTE: This only works for cases where the x
and y
values, i.e. the dividend and divisor, are represented accurately, even after any rounding to make them work as integers when they're larger than Number.MAX_SAFE_INTEGER
.
For example, if we have:
x = 45000000000000000000000000000 = 4.5e+28
y = 500000000000000000000000000 = 5e+26
Then the answers given on this page give you:
89.99999999999999: x/y
90: Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(Math.abs(x/y))))) * Math.sign(x/y))
89: Math.floor(x/y)
89: ~~(x/y)
89: (x/y)>>0
89: x/y|0
89: (x-(x%y))/y
The correct answer is 90
, so, as you can see, the equation I gave above is the only one which provides a correct answer.
The equation works for negative results as well. If we make x
negative then we get:
-89.99999999999999: x/y
-90: Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(Math.abs(x/y))))) * Math.sign(x/y))
-90: Math.floor(x/y)
-89: ~~(x/y)
-89: (x/y)>>0
-89: x/y|0
-89: (x-(x%y))/y
Only that equation and Math.floor()
give the correct answers.
And, just to confirm with some different values that give a slightly larger value:
x = -45000000000000000000000000 = -4.5e+25
y = 500000000000000000000000 = 5e+23
we get:
-90.00000000000001: x/y
-90: Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(Math.abs(x/y))))) * Math.sign(x/y))
-91: Math.floor(x/y)
-90: ~~(x/y)
-90: (x/y)>>0
-90: x/y|0
-90.00000000000001: (x-(x%y))/y
In this case, Math.floor()
and (x-(x%y))/y
fail, meaning that, while it may not be fast or pretty, the code given for this answer is the only method which gives correct results in all cases, provided that the divisor and dividend are able to be represented accurately. (Or, at least, all cases that I'm aware of.)
If you want to know how to get the correct remainder for large numbers, see:
Addendum: If you're only working with positive numbers, then you can shorten it to this:
Math.trunc((x/y) + (Number.EPSILON * (2 ** Math.ceil(Math.log2(x/y)))))
You can use the ternary operator to decide how to handle positive and negative integer values as well.
var myInt = (y > 0) ? Math.floor(y/x) : Math.floor(y/x) + 1
If the number is a positive, all is fine. If the number is a negative, it will add 1 because of how Math.floor handles negatives.
This will always truncate towards zero.
function intdiv(dividend, divisor) {
divisor = divisor - divisor % 1;
if (divisor == 0) throw new Error("division by zero");
dividend = dividend - dividend % 1;
var rem = dividend % divisor;
return {
remainder: rem,
quotient: (dividend - rem) / divisor
};
}
Here is a way to do this. (Personally I would not do it this way, but I thought it was a fun way to do it for an example.) The ways mentioned in previous answers are definitely better as this calls multiple functions and is therefore slower as well as takes up more room in your bundle.
function intDivide(numerator, denominator) {
return parseInt((numerator/denominator).toString().split(".")[0]);
}
let x = intDivide(4,5);
let y = intDivide(5,5);
let z = intDivide(6,5);
console.log(x);
console.log(y);
console.log(z);
© 2022 - 2025 — McMap. All rights reserved.
3.5 % 2
evaluates to 1.5. Make sure to handle (parseInt, floor, etc.) as required – Pudendum