A Leading Zeros Function

Although Javascript has an excellent method for attaching trailing zeros to decimals, there is no native function to attach leading zeros. For example, if you are dealing in currency, and want ten cents to appear as .10, instead of .1, you would just write:

00058

var theNumber = .1;

theNumber = theNumber.toFixed(2);

Javascript’s toFixed() is great for trailing zeros, but what if you wanted a fixed number of leading zeros? If you wanted 10 to display as 0010?

A leading zeros function is handy tool in any Javascript library, so let’s write one now. We’ll need two variables: a number to format and the number of digits. We’ll change the number into a string, then attach leading zeros until it has the correct number of digits:

function padZeros(theNumber, max) {

    var numStr = String(theNumber);

    

    while ( numStr.length 

The padZeros() function returns a string with the correct number of digits. For example:

alert(padZeros(610,5));

This would alert "00610".

Be Sociable, Share!

Tags: , ,