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
Math.floor(1+7/8)
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);
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
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990
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()
Was fiddling round with someone elses code today and found the following which seems rounds down as well:
var dec = 12.3453465,
int = dec >> 0; // returns 12
For more info on the Sign-propagating right shift(>>) see MDN Bitwise Operators
It took me a while to work out what this was doing :D
But as highlighted above, Math.floor() works and looks more readable in my opinion.