代码之家  ›  专栏  ›  技术社区  ›  mikasa

在javascript中,如何根据数字将数字四舍五入到最接近的100/1000?

  •  8
  • mikasa  · 技术社区  · 7 年前

    我有一个可以是2位数的数字,比如67、24、82,或者是3位数的数字,比如556、955、865或4位数等等。如何根据数字将数字四舍五入到最接近的N+1位?

    例子:

    roundup(87) => 100,
    roundup(776) => 1000,
    roudnup(2333) => 10000
    

    等等。

    5 回复  |  直到 6 年前
        1
  •  11
  •   Nina Scholz    7 年前

    function roundup(v) {
        return Math.pow(10, Math.ceil(Math.log10(v)));
    }
    
    console.log(roundup(87));   //   100
    console.log(roundup(776));  //  1000
    console.log(roundup(2333)); // 10000

    function roundup(v) {
        return (v >= 0 || -1) * Math.pow(10, 1 + Math.floor(Math.log10(Math.abs(v))));
    }
    
    console.log(roundup(87));    //    100
    console.log(roundup(-87));   //   -100
    console.log(roundup(776));   //   1000
    console.log(roundup(-776));  //  -1000
    console.log(roundup(2333));  //  10000
    console.log(roundup(-2333)); // -10000
        2
  •  7
  •   Jonas Wilms    7 年前
     const roundup = n => 10 ** ("" + n).length
    

        3
  •  4
  •   CertainPerformance    7 年前

    const roundup = num => 10 ** String(num).length;
    console.log(roundup(87));
    console.log(roundup(776));
    console.log(roundup(2333));
        4
  •  4
  •   Zenoo    7 年前

    String#repeat Number#toString

    const roundUp = number => +('1'+'0'.repeat(number.toString().length));
    
    console.log(roundUp(30));
    console.log(roundUp(300));
    console.log(roundUp(3000));
        5
  •  3
  •   Bilal Alam    7 年前

    //Math.pow(10,(value+"").length)   
    
    
    console.log(Math.pow(10,(525+"").length))
    console.log(Math.pow(10,(5255+"").length))

    推荐文章