How do I round a number in JavaScript?

后端 未结 8 2175
余生分开走
余生分开走 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:19

    Here is a way to be able to use Math.round() with a second argument (number of decimals for rounding):

    // 'improve' Math.round() to support a second argument
    var _round = Math.round;
    Math.round = function(number, decimals /* optional, default 0 */)
    {
      if (arguments.length == 1)
        return _round(number);
    
      var multiplier = Math.pow(10, decimals);
      return _round(number * multiplier) / multiplier;
    }
    
    // examples
    Math.round('123.4567', 2); // => 123.46
    Math.round('123.4567');    // => 123
    

提交回复
热议问题