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

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


当前回答

我只是偶然发现这篇文章寻找一个本地的解决方案。由于没有内置的解决方案,以下是我的看法:

function zerofill(number, width) {
    var num = '';
    while (width-- > 0) {
        num += '0';
    }

    return num.slice(0, - (number + '').length) + number + '';
}

其他回答

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

(也适用于负数和小数)

代码:

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'

一个简单的用例(填充毫秒从不> 999) 如果需要,您可以调整零的数量,或者使用更通用的方法。

/**
 * @val integer
 * @zeros padding
 */
function zeroFill(val, zeros)
{
    var str = val.toString();
    if (str.length >= zeros)
        return str;
    str = "000" + str;
    return str.substring(str.length - zeros);
}
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

…等。

干杯

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

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

简单的数学运算就可以得到一个单行函数:

function zeroFill( number, width ) {
  return Array(width - parseInt(Math.log(number)/Math.LN10) ).join('0') + number;
}

这是假设number是一个不大于width的整数。如果调用例程不能保证,函数将需要进行一些检查:

function zeroFill( number, width ) {
    var n = width - parseInt(Math.log(number)/Math.LN10);
    return (n < 0) ? '' + number : Array(n).join('0') + number;
}