How can I round down a number in Javascript?

220,540

Solution 1

Using Math.floor() is one way of doing this.

More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

Solution 2

Round towards negative infinity - Math.floor()

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

Round towards zero can be done using Math.trunc(). Older browsers do not support this function. If you need to support these, you can use 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;
alert( rounded );
//alerts "34"

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
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990

Solution 5

Rounding a number towards 0 (aka "truncating its fractional part") 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
Share:
220,540

Related videos on Youtube

Ben Shelock
Author by

Ben Shelock

i do internets and that

Updated on September 10, 2021

Comments

  • Ben Shelock
    Ben Shelock over 2 years

    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...

    • Daniel Brückner
      Daniel Brückner over 14 years
      Round towards zero or towards negative infinity?
  • Jason Berry
    Jason Berry over 14 years
    1+7/8 = 1 - Not much need for Math.floor() there :)
  • geraldalewis
    geraldalewis over 14 years
    It's also the slowest method; if you need to perform a lot of these, use the bitwise | operator (see my post).
  • Joe Phillips
    Joe Phillips over 14 years
    Actually it's (7/8)+1 which is not 1. Thank you 3rd grade algebra
  • DigitalRoss
    DigitalRoss over 14 years
    Or open the Firefox Error Console. Or Firebug. It isn't hard to try. I tried it. 1 + 7/8 is 1.875 in js. Did you possibly forget that all math in js is in floating point?
  • DigitalRoss
    DigitalRoss over 14 years
    It's probably easy to forget that javascript does everything in floating point. In many other languages 1+7/8 is 1, but in js it really is 1.875.
  • Jason S
    Jason S over 14 years
    ??? I just ran jsdb (www.jsdb.org) which uses Spidermonkey 1.7, and ran a loop to sum up the floor'ed value of x[i] on an array of 100000 floating point numbers, first with Math.floor(), then with bitwise or as you suggest. It took approx the same time, 125 msec.
  • Jason S
    Jason S over 14 years
    Just repeated the test with 500000 floating point numbers, it took approx the same time, approx 625 msec.
  • Jason S
    Jason S over 14 years
    So I don't see how 1.25usec is very slow.
  • geraldalewis
    geraldalewis over 14 years
    Can't argue with your data :) I think I may be have confused JS's implementation with ActionScript's (built on EcmaScript; obviously implementation differs). Thanks for checking my work!
  • Dominic Bou-Samra
    Dominic Bou-Samra over 14 years
    @Jason S: I don't think .5s is slow to do things, but it doesn't mean you shouldn't aim to be as quick as possible if you have the opportunity.
  • George
    George about 12 years
    Thank you for the completeness but the capitalization is wrong ... and in java-script that makes a HUGE difference. Otherwise I would have upvoted here.
  • chasen
    chasen almost 12 years
    I have updated the answer so that the capitalization is now correct.
  • Ry-
    Ry- over 11 years
    They don't do the same thing, either. | converts to a 32-bit integer, truncating; Math.floor rounds down. jsfiddle.net/minitech/UVG2w
  • Chris West
    Chris West over 11 years
    I agree 100% with minitech's comment. The main issue is the fact that if the number cannot be represented as a 32-bit number, using this method will result in an unexpected. On the other hand, if you know beforehand that the number will never be outside of the 32-bit range, you can use this approach instead.
  • m93a
    m93a over 10 years
    @George HUGE or huge? :D
  • Mike Godin
    Mike Godin about 10 years
    The | operator also rounds towards zero, not negative infinity.
  • Atmocreations
    Atmocreations about 9 years
    This has nothing to do with whether javascript uses floating point or not. It all boils down to operator precedence (en.wikipedia.org/wiki/Order_of_operations), so it should always be 1+(7/8), being valid in most programming languages
  • Matthias Urlichs
    Matthias Urlichs over 8 years
    It also silently kills your number if it doesn't fit in 32 bits. Chromium console: 99999999999999999999999|0 => -167772160
  • Ahmed Fasih
    Ahmed Fasih almost 8 years
    You can get the same effect as round-to-zero via x | 0.
  • jumxozizi
    jumxozizi over 7 years
    Actually @DigitalRoss is right. The difference between languages is the data type, not operator precedence. For example SQL returns an integer when doing math operations with integers. select 1+7/8 /* = 1 */, 7/8 /* = 0 */, 1.0+7.0/8.0 /* = 1.875000 */. Of course @JasonBerry 's mistake was the operator precedence.
  • Rick Mohr
    Rick Mohr over 3 years
    Great answer! Perhaps it should say "Truncating a number towards zero" rather than "Rounding ..."