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

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


当前回答

exports.pad = (num, length) => "0".repeat(length - num.toString().length) + num;

其他回答

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

(也适用于负数和小数)

代码:

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'

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

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

自ECMAScript 2017以来,我们有了padStart:

Const padding =(。1 +“”)。padStart(“0”); console.log(“- ${垫}”);

在ECMAScript 2017之前

toLocaleString:

为 n=-0.1; var res = n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false}); console.log(res);

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

例如:

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

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

这是我想出的一个快速函数。如果有人有更简单的方法,欢迎分享!

function zerofill(number, length) {
    // Setup
    var result = number.toString();
    var pad = length - result.length;

    while(pad > 0) {
        result = '0' + result;
        pad--;
    }

    return result;
}