How do I round a number in JavaScript?

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

    If you need to round to a certain number of digits use the following function

    function roundNumber(number, digits) {
                var multiple = Math.pow(10, digits);
                var rndedNum = Math.round(number * multiple) / multiple;
                return rndedNum;
            }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题