get floor value of division js
- Published
- Reading time
- 1 min read
- Length
- 306 words
On this page
Get Floor Value of Division in JavaScript#
When dividing two numbers in JavaScript, sometimes we need to get the floor value of the result. The floor value is the largest integer less than or equal to the result. For example, the floor value of 5 divided by 2 is 2.
Method 1: Using Math.floor()#
In JavaScript, we can use the Math.floor() method to get the floor value of a division. The Math.floor() method returns the largest integer less than or equal to a given number.
let result = Math.floor(5 / 2);
console.log(result); // Output: 2In the above example, we first divide 5 by 2 and then apply the Math.floor() method on the result to get the floor value.
Method 2: Using Bitwise Left Shift Operator#
Another way to get the floor value of a division in JavaScript is by using the bitwise left shift operator (<<). The bitwise left shift operator shifts the bits of a number to the left by a specified number of positions.
We can use this operator to divide a number by 2 and get its floor value. For example, 5 >> 1 will give us 2.
let result = 5 >> 1;
console.log(result); // Output: 2In the above example, we use the bitwise left shift operator to divide 5 by 2 and get its floor value.
Method 3: Using Division and Math.trunc()#
In JavaScript, we can also use the division operator (/) and the Math.trunc() method to get the floor value of a division. The Math.trunc() method returns the integer part of a number by removing any fractional digits.
let result = Math.trunc(5 / 2);
console.log(result); // Output: 2In the above example, we first divide 5 by 2 and then apply the Math.trunc() method on the result to get the floor value.