Zero Format //JavaScript Repository

Description

Adds zeros on the left or right of a number.
Created: 2005.10.02 - Modified 2005.11.01

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/number/zero-format [rev. #1]

Number.prototype.zeroFormat = function(n, f, r){
    return n = new Array((++n, f ? (f = (this + "").length) < n ? n - f : 0 : n)).join(0), r ? this + n : n + this;
};

Example (Example)

<script type="text/javascript">
//<![CDATA[

var n = 123;
document.write(
    "<h2>N = ", n, "</h2>",
    "N.zeroFormat(5, true, true) = ", n.zeroFormat(5, true, true), "<br />",
    "N.zeroFormat(5, true) = ", n.zeroFormat(5, true), "<br />",
    "N.zeroFormat(5) = ", n.zeroFormat(5)
);

//]]>
</script>

Help

Number.zeroFormat(n: Integer, [fill: Boolean = false], [right: Boolean = false]): String
Returns the number converted to string with zeroes on the left or right.
n
amount of zeroes to be added
fill
if "true", the zeroes will be added to the number until reaching at least "n" digits, otherwise it will be added exactly "n" zeroes
right
if "true" the zeroes will be concatenated on the right, otherwise on the left

Rank (Votes: 43)

3.79