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

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


当前回答

我经常使用这个结构来填充某个值n,已知是一个正的小数:

(offset + n + '').substr(1);

其中偏移量为10^^位。

例如,填充到5位数,其中n = 123:

(1e5 + 123 + '').substr(1); // => 00123

十六进制的版本稍微详细一些:

(0x100000 + 0x123).toString(16).substr(1); // => 00123

注1:我也喜欢@profitehlolz的解决方案,它是这个的字符串版本,使用slice()的漂亮的负索引特性。

其他回答

这个方法不是更快,但它相当原生。

zeroPad = function (num, count) {
    return [Math.pow(10, count - num.toString().length), num].join('').substr(1);
};
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

…等。

干杯

我不敢相信这里有这么多复杂的答案……就用这个吧:

var zerofilled = ('0000'+n).slice(-4);

让n = 1 var zerofilled = ('0000' n).切片(4); 控制台日志(zerofilled)。

我使用这个片段来获得一个五位数的表示:

(value+100000).toString().slice(-5) // "00123" with value=123

我在这个表单中没有看到任何答案所以这里是我的正则表达式和字符串操作

(也适用于负数和小数)

代码:

function fillZeroes(n = 0, m = 1) {
  const p = Math.max(1, m);
  return String(n).replace(/\d+/, x => '0'.repeat(Math.max(p - x.length, 0)) + x);
}

输出:

console.log(fillZeroes(6, 2))          // >> '06'
console.log(fillZeroes(1.35, 2))       // >> '01.35'
console.log(fillZeroes(-16, 3))        // >> '-016'
console.log(fillZeroes(-1.456, 3))     // >> '-001.456'
console.log(fillZeroes(-456.53453, 6)) // >> '-000456.53453'
console.log(fillZeroes('Agent 7', 3))  // >> 'Agent 007'