How can I round down a number in Javascript?

前端 未结 11 1359
感动是毒
感动是毒 2020-11-29 23:27

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

相关标签:
11条回答
  • 2020-11-30 00:06
    Math.floor(1+7/8)
    
    0 讨论(0)
  • 2020-11-30 00:10

    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);
    
    0 讨论(0)
  • 2020-11-30 00:12

    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
    
    0 讨论(0)
  • 2020-11-30 00:13

    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()
    
    0 讨论(0)
  • 2020-11-30 00:18

    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.

    0 讨论(0)
提交回复
热议问题