Skip to content
the poor coder

get floor value of division js

Poor Man
Published
Reading time
1 min read
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.

Text

let result = Math.floor(5 / 2);
console.log(result); // Output: 2

In 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.

Text

let result = 5 >> 1;
console.log(result); // Output: 2

In 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.

Text

let result = Math.trunc(5 / 2);
console.log(result); // Output: 2

In the above example, we first divide 5 by 2 and then apply the Math.trunc() method on the result to get the floor value.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC