Integer division in Javascript

All numbers in javascript are doubles. This means no integer division by default.

if you do this:

var result = 5/4;//1.25

the expected result is 1, but the answer is 1.25

Integer division can easily be achieved by flooring the quotient of the two numbers, using Math.floor

var result = Math.floor(5/4);//1

This leads to a problem though. What if you had a situation like this:

var result = Math.floor(-5/4);//-2

In this case the quotient is negative. The expected answer is -1, but you’ll get -2 instead. Flooring works the opposite way for negative numbers. An if statement can fix this:

var result = -5/4;
result = Math.floor(result);
result = Math.ceil(result);

Math.ceil works like Math.floor for negative numbers

This is however slower, since you have to use an if statement. Use Math.floor when you certain the value is positive, otherwise use this this little function:

function intDiv(a,b)
var result = a/b;
return Math.floor(result);
return Math.ceil(result);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s