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

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


当前回答

我在这里寻找一个标准,和保罗和约拿单有同样的想法……他们的照片超级可爱,但这里有一个非常可爱的版本:

function zeroPad(n, l, i) {
    return (i = n/Math.pow(10, l))*i > 1 ? '' + n : i.toFixed(l).replace('0.', '');
}

这也可以(我们假设是整数,对吗?)…

> zeroPad(Math.pow(2, 53), 20);
'00009007199254740992'

> zeroPad(-Math.pow(2, 53), 20);
'-00009007199254740992'

> zeroPad(Math.pow(2, 53), 10);
'9007199254740992'

> zeroPad(-Math.pow(2, 53), 10);
'-9007199254740992'

其他回答

ES6让这一点变得相当微不足道:

function pad (num, length, countSign = true) {
  num = num.toString()
  let negative = num.startsWith('-')
  let numLength = negative && !countSign ? num.length - 1 : num.length
  if (numLength >= length) {
    return num
  } else if (negative) {
    return '-' + '0'.repeat(length - numLength) + num.substr(1)
  } else {
    return '0'.repeat(length - numLength) + num
  }
}

pad(42, 4)          === '0042'
pad(12345, 4)       === '12345'
pad(-123, 4)        === '-100'
pad(-123, 4, false) === '-0100'

一个简单优雅的解,n是数字,l是长度。

函数nFill (n, l){返回(l > n.toString () . length) ?((数组(l) . join(“0”)+ n) .slice (- l)): n;}

这将保持长度,如果它是超过所需的,而不是改变数字。

N = 500; console.log (nFill (n, 5)); console.log (nFill (n, 2)); 函数nFill (n, l){返回(l > n.toString () . length) ?((数组(l) . join(“0”)+ n) .slice (- l)): n;}

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

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

这里有一个我认为很酷的小技巧:

(2/10000).toString().split(".")[1]
"0002"
(52/10000).toString().split(".")[1]
"0052"

仅供参考,更清晰,更可读的语法恕我直言

"use strict";
String.prototype.pad = function( len, c, left ) {
    var s = '',
        c = ( c || ' ' ),
        len = Math.max( len, 0 ) - this.length,
        left = ( left || false );
    while( s.length < len ) { s += c };
    return ( left ? ( s + this ) : ( this + s ) );
}
Number.prototype.pad = function( len, c, left ) {
    return String( this ).pad( len, c, left );
}
Number.prototype.lZpad = function( len ) {
    return this.pad( len, '0', true );
}

这也导致结果的视觉和可读性问题比其他一些解决方案更少,这些解决方案强制'0'作为字符;回答我的问题,我该怎么做,如果我想垫其他字符,或在其他方向(右填充),同时保持容易打字,并清楚地阅读。我敢肯定,这也是DRY的最佳示例,实际的前导零填充函数体的代码最少(因为其他相关函数在很大程度上与这个问题无关)。

该代码可通过github用户的gist进行评论(代码的原始来源) https://gist.github.com/Lewiscowles1986/86ed44f428a376eaa67f

在控制台和脚本测试中注意,数值文字似乎需要括号或变量才能调用方法,因此2.pad(…)将导致错误,而(2).pad(0,'#')不会。这似乎对所有数字都是一样的