# 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);
}

```