How can I pad a value with leading zeros?

2018-12-30 23:59发布

What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?

Note: By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005").

30条回答
美炸的是我
2楼-- · 2018-12-31 00:52

I really don't know why, but no one did it in the most obvious way. Here it's my implementation.

Function:

/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
    var num = number+"";
    while(num.length < digits){
        num='0'+num;
    }
    return num;
}

Prototype:

Number.prototype.zeroPad=function(digits){
    var num=this+"";
    while(num.length < digits){
        num='0'+num;
    }
    return(num);
};

Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.

查看更多
泛滥B
3楼-- · 2018-12-31 00:52

First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.

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'
查看更多
一个人的天荒地老
4楼-- · 2018-12-31 00:53

The power of Math!

x = integer to pad
y = number of zeroes to pad

function zeroPad(x, y)
{
   y = Math.max(y-1,0);
   var n = (x / Math.pow(10,y)).toFixed(y);
   return n.replace('.','');  
}
查看更多
与君花间醉酒
5楼-- · 2018-12-31 00:53
function pad(toPad, padChar, length){
    return (String(toPad).length < length)
        ? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
        : toPad;
}

pad(5, 0, 6) = 000005

pad('10', 0, 2) = 10 // don't pad if not necessary

pad('S', 'O', 2) = SO

...etc.

Cheers

查看更多
深知你不懂我心
6楼-- · 2018-12-31 00:54

Note to readers!

As commenters have pointed out, this solution is "clever", and as clever solutions often are, it's memory intensive and relatively slow. If performance is a concern for you, don't use this solution!

Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:

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

...will output "-0000.10".

// or 
const padded = (.1+"").padStart(6,"0");
`-${padded}`

...will output "-0000.1".

A simple function is all you need

function zeroFill( number, width )
{
  width -= number.toString().length;
  if ( width > 0 )
  {
    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
  }
  return number + ""; // always return a string
}

you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.

查看更多
公子世无双
7楼-- · 2018-12-31 00:54

I use this snipet to get a 5 digits representation

(value+100000).toString().slice(-5) // "00123" with value=123
查看更多
登录 后发表回答