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

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


当前回答

我的解决方案

Number.prototype.PadLeft = function (length, digit) {
    var str = '' + this;
    while (str.length < length) {
        str = (digit || '0') + str;
    }
    return str;
};

使用

var a = 567.25;
a.PadLeft(10); // 0000567.25

var b = 567.25;
b.PadLeft(20, '2'); // 22222222222222567.25

其他回答

数学的力量!

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('.','');  
}

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

例如:

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

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

如果性能真的很关键(遍历数百万条记录),则可以预先生成填充字符串数组,从而避免每次调用都这样做。

时间复杂度:O(1)。 空间复杂度:O(1)。

const zeroPads = Array.from({ length: 10 }, (_, v) => '0'.repeat(v)) 函数 zeroPad(num, len) { const numStr = String(num) return (zeroPads[len - numStr.length] + numStr) }

Use:

function zfill(num, len) {
  return(0 > num ? "-" : "") + (Math.pow(10, len) <= Math.abs(num) ? "0" + Math.abs(num) : Math.pow(10, len) + Math.abs(num)).toString().substr(1)
}

这可以处理负数和数字比字段宽度长的情况。和浮点。

一些monkeypatching也可以工作

String.prototype.padLeft = function (n, c) {
  if (isNaN(n))
    return null;
  c = c || "0";
  return (new Array(n).join(c).substring(0, this.length-n)) + this; 
};
var paddedValue = "123".padLeft(6); // returns "000123"
var otherPadded = "TEXT".padLeft(8, " "); // returns "    TEXT"