Truncate/round whole number in JavaScript?

前端 未结 6 1037
长发绾君心
长发绾君心 2020-12-24 00:11

For a script I\'m writing, I need display a number that has been rounded, but not the decimal or anything past it. I\'ve gotten down to rounding it to the third place, but I

6条回答
  •  误落风尘
    2020-12-24 01:00

    Convert the number to a string and throw away everything after the decimal.

    trunc = function(n) { return Number(String(n).replace(/\..*/, "")) }
    
    trunc(-1.5) === -1
    
    trunc(1.5) === 1
    

    Edit 2013-07-10

    As pointed out by minitech and on second thought the string method does seem a bit excessive. So comparing the various methods listed here and elsewhere:

    function trunc1(n){ return parseInt(n, 10); }
    function trunc2(n){ return n - n % 1; }
    function trunc3(n) { return Math[n > 0 ? "floor" : "ceil"](n); }
    function trunc4(n) { return Number(String(n).replace(/\..*/, "")); }
    
    function getRandomNumber() { return Math.random() * 10; }
    
    function test(func, desc) {
        var t1, t2;
        var ave = 0;
        for (var k = 0; k < 10; k++) {
            t1 = new Date().getTime();
            for (var i = 0; i < 1000000; i++) {
                window[func](getRandomNumber());
            }
            t2 = new Date().getTime();
            ave += t2 - t1;
        }
        console.info(desc + " => " + (ave / 10));
    }
    
    test("trunc1", "parseInt");
    test("trunc2", "mod");
    test("trunc3", "Math");
    test("trunc4", "String");
    

    The results, which may vary based on the hardware, are as follows:

    parseInt => 258.7
    mod      => 246.2
    Math     => 243.8
    String   => 1373.1
    

    The Math.floor / ceil method being marginally faster than parseInt and mod. String does perform poorly compared to the other methods.

提交回复
热议问题