在 JavaScript 中格式化数字

Formatting Number in JavaScript

本文关键字:数字 格式化 JavaScript      更新时间:2023-09-26

可能的重复项:
Javascript 在字符串的开头添加零(最大长度 4 个字符(
JavaScript格式编号为2位数字

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

9   => 009
99  => 099
100 => 100

这是微不足道的。

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

您可以自己轻松地将其转换为功能。

function pad(number, length) 
{
    var result = number.toString();
    var temp = length - result.length;
    while(temp > 0) 
    {
        result = '0' + result;
        temp--;
    }
    return result;
}

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

你可以对数字进行 String((,然后检查他的长度(NUMLENGTH(,如果它小于你需要的总位数 (MAXDIGITS(,然后在字符串前面加上 MAXDIGITS-NUMLENGTH 零。

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);
}
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;
}