TL ; DR:
The
Math.floor()function returns the largest integer less than or equal to a given number:console.log(Math.floor(3.9)); // Output: 3 console.log(Math.floor(5.2)); // Output: 5 console.log(Math.floor(7)); // Output: 7We can use this function if we want to compute the integral part of some division (quotient):
let a = 3; let b = 7; console.log(Math.floor(20 / a)); // Output: 6 console.log(Math.floor(b / a)); // Output: 2
Full lesson:
Remember how we first learn about the division of two integer numbers in primary school?
The quotient is the number of times a division is completed fully, while the remainder is the amount left that doesn't entirely go into the divisor.
Here are some examples:
10 / 2 = quotient 5, remainder 0
15 / 4 = quotient 3, remainder 3
20 / 3 = quotient 6, remainder 2
Floor division
Floor division is a normal division operation except that it returns the integral part of the result (the quotient). TypeScript has no operator for it (// starts a comment), and / always gives a decimal result (7 / 2 is 3.5), so we round the result down with Math.floor:
console.log(Math.floor(10 / 2)); // Output: 5
console.log(Math.floor(15 / 4)); // Output: 3
console.log(Math.floor(20 / 3)); // Output: 6
It can also be used with variables:
let a = 3;
let b = 7;
console.log(Math.floor(20 / a)); // Output: 6
console.log(Math.floor(b / a)); // Output: 2
Modulo
The modulo operator (%) calculates the remainder of dividing two values:
console.log(10 % 2); // Output: 0
console.log(15 % 4); // Output: 3
console.log(20 % 3); // Output: 2
// Can be used with variables:
let c = 2;
let d = 4;
console.log(d % c); // Output: 0
console.log(11 % d); // Output: 3
Quotient and remainder
In programming, we combine both these concepts to get the quotient and remainder of some divison:
// Let's divide 26 by 3:
const quotient = Math.floor(26 / 3);
const remainder = 26 % 3;
console.log(quotient); // Output: 8
console.log(remainder); // Output: 2
Assignment
Follow the Coding Tutorial and let's practice with quotient and remainder!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
