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

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


当前回答

快速而肮脏的方式:

y = (new Array(count + 1 - x.toString().length)).join('0') + x;

当x = 5 count = 6时y = "000005"

其他回答

这是你能找到的最简单、最直接的解决方案。

function zerofill(number,length) {
    var output = number.toString();
    while(output.length < length) {
      output = '0' + output;
    }
    return output;
}

并不是说这个问题需要更多的答案,但我认为我应该添加这个简单的lodash版本。

_。屏幕左边(6号,0号)

function zeroPad(num,digits){ return ((num/Math.pow(10,digits))+'').slice(2) } 

我发现这个问题很有趣,我贡献了自己的一份力量

function zeroLeftComplete(value, totalCharters = 3) { const valueString = value.toString() || '0' const zeroLength = valueString.length - totalCharters if (Math.sign(parseInt(zeroLength)) === -1) { const zeroMissing = Array.from({ length: Math.abs(zeroLength) }, () => '0').join('') return `${zeroMissing}${valueString}` } else return valueString }; console.log(zeroLeftComplete(0)); console.log(zeroLeftComplete(1)); console.log(zeroLeftComplete(50)); console.log(zeroLeftComplete(50561,3));

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'