Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I actually had to come up with something like this recently. I figured there had to be a way to do it without using loops.</p> <p>This is what I came up with.</p> <pre><code>function zeroPad(num, numZeros) { var n = Math.abs(num); var zeros = Math.max(0, numZeros - Math.floor(n).toString().length ); var zeroString = Math.pow(10,zeros).toString().substr(1); if( num &lt; 0 ) { zeroString = '-' + zeroString; } return zeroString+n; } </code></pre> <p>Then just use it providing a number to zero pad:</p> <pre><code>&gt; zeroPad(50,4); "0050" </code></pre> <p>If the number is larger than the padding, the number will expand beyond the padding:</p> <pre><code>&gt; zeroPad(51234, 3); "51234" </code></pre> <p>Decimals are fine too!</p> <pre><code>&gt; zeroPad(51.1234, 4); "0051.1234" </code></pre> <p>If you don't mind polluting the global namespace you can add it to Number directly:</p> <pre><code>Number.prototype.leftZeroPad = function(numZeros) { var n = Math.abs(this); var zeros = Math.max(0, numZeros - Math.floor(n).toString().length ); var zeroString = Math.pow(10,zeros).toString().substr(1); if( this &lt; 0 ) { zeroString = '-' + zeroString; } return zeroString+n; } </code></pre> <p>And if you'd rather have decimals take up space in the padding:</p> <pre><code>Number.prototype.leftZeroPad = function(numZeros) { var n = Math.abs(this); var zeros = Math.max(0, numZeros - n.toString().length ); var zeroString = Math.pow(10,zeros).toString().substr(1); if( this &lt; 0 ) { zeroString = '-' + zeroString; } return zeroString+n; } </code></pre> <p>Cheers!</p> <hr> <hr> <p><a href="https://stackoverflow.com/users/2030088/xdr">XDR</a> came up with <strong>a logarithmic variation</strong> that seems to perform better.</p> <p><strong>WARNING</strong>: This function fails if num equals zero (e.g. zeropad(0, 2))</p> <pre><code>function zeroPad (num, numZeros) { var an = Math.abs (num); var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10); if (digitCount &gt;= numZeros) { return num; } var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1); return num &lt; 0 ? '-' + zeroString + an : zeroString + an; } </code></pre> <hr> <p>Speaking of performance, <a href="https://stackoverflow.com/users/1608468/tomsmeding">tomsmeding</a> <a href="http://jsperf.com/left-zero-pad" rel="noreferrer">compared the top 3 answers</a> (<a href="http://jsperf.com/left-zero-pad/10" rel="noreferrer">4 with the log variation</a>). Guess which one <em>majorly</em> outperformed the other two? :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload