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

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


当前回答

第一个参数是任何实数,第二个参数是一个正整数,指定小数点左边的最小位数,第三个参数是一个可选的正整数,指定小数点右边的数字。

function zPad(n, l, r){
    return(a=String(n).match(/(^-?)(\d*)\.?(\d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
}

so

           zPad(6, 2) === '06'
          zPad(-6, 2) === '-06'
       zPad(600.2, 2) === '600.2'
        zPad(-600, 2) === '-600'
         zPad(6.2, 3) === '006.2'
        zPad(-6.2, 3) === '-006.2'
      zPad(6.2, 3, 0) === '006'
        zPad(6, 2, 3) === '06.000'
    zPad(600.2, 2, 3) === '600.200'
zPad(-600.1499, 2, 3) === '-600.149'

其他回答

我对这个话题的一点贡献(https://gist.github.com/lucasferreira/a881606894dde5568029):

/* Autor: Lucas Ferreira - http://blog.lucasferreira.com | Usage: fz(9) or fz(100, 7) */
function fz(o, s) {
    for(var s=Math.max((+s||2),(n=""+Math.abs(o)).length); n.length<s; (n="0"+n));
    return (+o < 0 ? "-" : "") + n;
};

用法:

fz(9) & fz(9, 2) == "09"
fz(-3, 2) == "-03"
fz(101, 7) == "0000101"

我知道,这是一个很脏的函数,但它很快,即使是负数也能工作;)

function zFill(n,l){
    return 
      (l > n.toString().length) ? 
        ( (Array(l).join('0') + n).slice(-l) ) : n;
}

如果npm在你的环境中可用,可以使用一些现成的包:www.npmjs.com/browse/keyword/zeropad。

我喜欢零填充。

安装

$ npm install zero-fill

使用

var zeroFill = require('zero-fill')

zeroFill(4, 1)      // '0001' 
zeroFill(4, 1, '#') // '###1' custom padding
zeroFill(4)(1)      // '0001' partials

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'

我在写一个数字基础转换器时,想到了一个荒谬的单行程序。

//这是被诅咒的 函数p (i, w、z) {z z = | | 0; w = w | | 8; i + = "; var o w = i.length %;还啊?[…数组(言).fill (z),……我]. join():我;} console.log (p (8675309));//默认:pad w/ 0到8位 console.log (p(525600年,10));//输入10个数字 console.log(p(69420, 10, 'X'));// Pad w/ X到10位 console.log (p (8675309, 4));//输入4位数字 console.log (p (12345678));//没必要就别拍

或者,以一种不那么容易暴露我把灵魂出卖给黑Perl的形式:

function pad(input, width, zero) {
    zero = zero || 0; width = width || 8;  // Defaults
    input += '';                           // Convert input to string first

    var overflow = input.length % width    // Do we overflow?
    if (overflow) {                        // Yep!  Let's pad it...
        var needed = width - overflow;     // ...to the next boundary...
        var zeroes = Array(needed);        // ...with an array...
        zeroes = zeroes.fill(zero);        // ...full of our zero character...
        var output = [...zeroes,...input]; // ...and concat those zeroes to input...
        output = output.join('');          // ...and finally stringify.
    } else {
        var output = input;                // We don't overflow; no action needed :)
    }

    return output;                         // Done!
}

这个答案与其他答案不同的一点是,它取数字长度对目标宽度的模,而不是简单的大于检查。如果你想确保结果长度是目标宽度的倍数(例如,你需要输出5或10个字符长),这是很方便的。

我不知道它的性能有多好,但是,嘿,至少它已经被缩小了!