JavaScript

How to execute an integer division in JavaScript

April 19, 2022

How to execute an integer division in JavaScript

In this article you will learn how to make an integer division in JavaScript, in a simple way, using native resources of the language itself.

integer division in JavaScript thumb

Hey you programmer, let’s learn more about JavaScript and math operations!

Normal division in JavaScript is done by the / symbol

Check out this example:

3/2 -> 1.5

However, we will receive a floating point number as a result if the division is not exact.

So what’s the alternative to creating an integer division?

The main alternative is to round the result down, thus eliminating the house after the decimal point.

To help us with this function we can use the floor method of the Math library

See an example:

const division = Math.floor(3/2)
console.log(division) // 1

This way we will get a result of an integer number, which solves our problem

Other languages already have integer division as a result by default, JavaScript is not one of them

We have to adapt a solution to obtain this result, as mentioned before, the floor method is the most used for this case

Conclusion

In this article we learned  how to perform an integer division in JavaScript

In fact, the language natively will always give us a float, in case the result is broken.

So the main alternative for this case is using the floor method of Math, like this: Math.floor(division)

So we will receive the result with an integer number, which solves our problem in this case of integer division, when the result of the operation gives a broken number

Do you want learn more about JavaScript? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x