How can I round down a number in Javascript?

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

    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 );
    

提交回复
热议问题