How do I round a number in JavaScript?

后端 未结 8 2163
余生分开走
余生分开走 2020-11-27 03:20

While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of

Name : Value
Name2 : Value2         


        
8条回答
  •  借酒劲吻你
    2020-11-27 04:07

    You hav to convert your input into a number and then round them:

    function toInteger(number){ 
      return Math.round(  // round to nearest integer
        Number(number)    // type cast your input
      ); 
    };
    

    Or as a one liner:

    function toInt(n){ return Math.round(Number(n)); };
    

    Testing with different values:

    toInteger(2.5);           // 3
    toInteger(1000);          // 1000
    toInteger("12345.12345"); // 12345
    toInteger("2.20011E+17"); // 220011000000000000
    

提交回复
热议问题