How can I round down a number in Javascript?

前端 未结 11 1377
感动是毒
感动是毒 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: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
    

提交回复
热议问题