在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?

注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。


当前回答

我们的测试是假的,因为我的有个错别字。

zeroPad = function (num, count) {
    return ((num / Math.pow(10, count)) + '').substr(2);
};

Paul的是最快的,但我认为.substr比.slice快,即使它多了一个字符;)

其他回答

ES6让这一点变得相当微不足道:

function pad (num, length, countSign = true) {
  num = num.toString()
  let negative = num.startsWith('-')
  let numLength = negative && !countSign ? num.length - 1 : num.length
  if (numLength >= length) {
    return num
  } else if (negative) {
    return '-' + '0'.repeat(length - numLength) + num.substr(1)
  } else {
    return '0'.repeat(length - numLength) + num
  }
}

pad(42, 4)          === '0042'
pad(12345, 4)       === '12345'
pad(-123, 4)        === '-100'
pad(-123, 4, false) === '-0100'

Use:

function zfill(num, len) {
  return(0 > num ? "-" : "") + (Math.pow(10, len) <= Math.abs(num) ? "0" + Math.abs(num) : Math.pow(10, len) + Math.abs(num)).toString().substr(1)
}

这可以处理负数和数字比字段宽度长的情况。和浮点。

我使用

Utilities.formatString("%04d", iThe_TWO_to_FOUR_DIGIT) 

哪个前导有4个0

注:这需要谷歌的应用程序脚本实用程序:

https://developers.google.com/apps-script/reference/utilities/utilities#formatstringtemplate-args

function pad(toPad, padChar, length){
    return (String(toPad).length < length)
        ? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
        : toPad;
}

Pad (5,0,6) = 000005

Pad('10', 0,2) = 10 //如果没有必要,不要填充

pad('S', 'O', 2) = SO

…等。

干杯

要填充数字的末尾,使用num.toFixed

例如:

  document.getElementById('el').value = amt.toFixed(2);

这是我找到的最简单的解决办法,而且很有效。