# How can I round down a number in Javascript?

## How can I round down a number in Javascript?

How can I round down a number in JavaScript?
math.round() doesn’t work because it rounds it to the nearest decimal.
I’m not sure if there is a better way of doing it other than breaking it apart at the decimal point at keeping the first bit. There must be…

### Solution 1:

``````Math.floor()
``````

### Solution 2:

Round towards negative infinity – `Math.floor()`

``````+3.5 => +3.0
-3.5 => -4.0
``````

Round towards zero – usually called `Truncate()`, but not supported by JavaScript – can be emulated by using `Math.ceil()` for negative numbers and `Math.floor()` for positive numbers.

``````+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()
``````

### Solution 3:

`Math.floor()` will work, but it’s very slow compared to using a bitwise `OR` operation:

``````var rounded = 34.923 | 0;
``````

EDIT `Math.floor()` is not slower than using the | operator. Thanks to Jason S for checking my work.

Here’s the code I used to test:

``````var a = [];
var time = new Date().getTime();
for( i = 0; i < 100000; i++ ) {
//a.push( Math.random() * 100000  | 0 );
a.push( Math.floor( Math.random() * 100000 ) );
}
var elapsed = new Date().getTime() - time;
alert( "elapsed time: " + elapsed );
``````

### Solution 4:

You can try to use this function if you need to round down to a specific number of decimal places

``````function roundDown(number, decimals) {
decimals = decimals || 0;
return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) );
}
``````

examples

``````alert(roundDown(999.999999)); // 999
``````

### Solution 5:

To round down towards negative infinity, use:

``````rounded=Math.floor(number);
``````

To round down towards zero (if the number can round to a 32-bit integer between -2147483648 and 2147483647), use:

``````rounded=number|0;
``````

To round down towards zero (for any number), use:

``````if(number>0)rounded=Math.floor(number);else rounded=Math.ceil(number);
``````

### Solution 6:

Rounding a `number` towards `0` can be done by subtracting its signed fractional part `number % 1`:

``````rounded = number - number % 1;
``````

Like `Math.floor` (rounds towards `-Infinity`) this method is perfectly accurate.

There are differences in the handling of `-0`, `+Infinity` and `-Infinity` though:

``````Math.floor(-0) => -0
-0 - -0 % 1    => +0

Math.floor(Infinity)    => Infinity
Infinity - Infinity % 1 => NaN

Math.floor(-Infinity)     => -Infinity
-Infinity - -Infinity % 1 => NaN
``````