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;
if(result>=0)
result = Math.floor(result);
else
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;
if(result>=0)
return Math.floor(result);
else
return Math.ceil(result);
}

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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