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

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


当前回答

数学的力量!

X = integer to pad Y =要填充的零的个数

function zeroPad(x, y)
{
   y = Math.max(y-1,0);
   var n = (x / Math.pow(10,y)).toFixed(y);
   return n.replace('.','');  
}

其他回答

js是一个完整的开源JavaScript sprintf实现 对于浏览器和node.js。 它的原型很简单: 字符串sprintf(字符串格式,[mixed arg1 [, mixed arg2[,…]]])

我想推荐Alexandru meurratisteanu的sprintf模块,整个解决方案看起来就像这样:

var sprintf = require('sprintf');
var zeroFilled = sprintf('%06d', 5);

console.log(zeroFilled); // 000005

注:我是在6年后回答这个问题,但似乎这个 问题成为“javascript零领先”参考考虑 浏览量和回答量都很高。

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

zeroPad = function (num, count) {
    return [Math.pow(10, count - num.toString().length), num].join('').substr(1);
};
exports.pad = (num, length) => "0".repeat(length - num.toString().length) + num;
function zeroPad(num,digits){ return ((num/Math.pow(10,digits))+'').slice(2) } 

这是我用来填充7个字符的数字。

("0000000" + number).slice(-7)

这种方法可能对大多数人来说已经足够了。

编辑:如果你想让它更通用,你可以这样做:

("0".repeat(padding) + number).slice(-padding)

编辑2:注意,自ES2017以来,你可以使用String.prototype.padStart:

number.toString().padStart(padding, "0")