Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p><strong><em>Note to readers!</em></strong></p> <p>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!</p> <p><strong><em>Potentially outdated</em></strong>: ECMAScript 2017 includes <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart" rel="noreferrer">String.prototype.padStart</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString" rel="noreferrer">Number.prototype.toLocaleString</a> is there since ECMAScript 3.1. Example:</p> <pre><code>var n=-0.1; n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false}) </code></pre> <p>...will output "-0000.10".</p> <pre><code>// or const padded = (.1+"").padStart(6,"0"); `-${padded}` </code></pre> <p>...will output "-0000.1".</p> </blockquote> <p>A simple function is all you need</p> <pre><code>function zeroFill( number, width ) { width -= number.toString().length; if ( width &gt; 0 ) { return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number; } return number + ""; // always return a string } </code></pre> <p>you could bake this into a library if you want to conserve namespace or whatever. Like with <a href="http://docs.jquery.com/Core/jQuery.extend#object" rel="noreferrer">jQuery's extend</a>.</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