【问题标题】:Formatting Number in JavaScript [duplicate]在 JavaScript 中格式化数字 [重复]
【发布时间】:2012-01-28 16:58:11
【问题描述】:

可能重复:
Javascript adding zeros to the beginning of a string (max length 4 chars)
javascript format number to have 2 digit

如何将数字格式化为 3 位数字,例如..

9   => 009

99  => 099

100 => 100

【问题讨论】:

标签: javascript formatting


【解决方案1】:

这是微不足道的。

var num = 9;
num = ""+num;
while(num.length < 3) num = "0"+num;

你可以自己轻松地把它变成一个函数。

【讨论】:

    【解决方案2】:
    function pad(number, length) 
    {
        var result = number.toString();
        var temp = length - result.length;
    
        while(temp > 0) 
        {
            result = '0' + result;
            temp--;
        }
    
        return result;
    }
    

    【讨论】:

      【解决方案3】:

      您当然需要将这些数字转换为字符串,因为数字数据类型不“支持”初始零。

      您可以 toString() 数字,然后检查他的长度 (NUMLENGTH),如果它小于您需要的总位数 (MAXDIGITS),然后在字符串前面加上 MAXDIGITS-NUMLENGTH 个零。

      【讨论】:

        【解决方案4】:

        http://jsfiddle.net/K3mwV/

        String.prototype.repeat = function( num ) {
            return new Array( num + 1 ).join( this );
        }
        for (i=1;i <= 100;i++) {
            e = i+'';
            alert('0'.repeat(3 - e.length)+i);
        }
        

        【讨论】:

          【解决方案5】:
          function padZeros(zeros, n) {
            // convert number to string
            n = n.toString();
            // cache length
            var len = n.length;
          
            // if length less then required number of zeros
            if (len < zeros) {
              // Great a new Array of (zeros required - length of string + 1)
              // Then join those elements with the '0' character and add it to the string
              n = (new Array(zeros - len + 1)).join('0') + n;
            }
            return n;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-07-04
            • 2015-06-07
            • 1970-01-01
            • 2017-02-19
            • 1970-01-01
            • 2020-02-26
            • 1970-01-01
            • 2013-12-10
            相关资源
            最近更新 更多