[thelist] javascript question on formatting numbers.

.jeff jeff at members.evolt.org
Thu Dec 20 16:50:29 CST 2001


><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: Richard Bennett
>
> I've done something like that for displaying timers in
> Javascript. What I wanted was 0-9 to have a leading 0,
> so all numbers had two digits:
>
> pad = function(int) {
>       return int=(int<10)?"0"+int:int
> }
>
> So,
>
> status=pad(3)
>
> will show 03
>
> You can do this with more zeros, but you'll want to use
> a switch to cater for the different values.
>
> Don't forget that these are no longer integers, but
> strings now, so if you want to do any calculations
> with them you should parseInt() them.
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

or for those of you who don't like using the odd function declaration above,
try this instead:

function pad(int)
{
  return int = (int < 10) ? '0 ' + int : int;
}

of course there's always the NumberFormat() function which lets you specify
any number of leading zeros, along with comma and decimal point placement,
etc., but no one has taken the time to write one that i've found.  *grin*
maybe i'll do that real soon now™

.jeff

http://evolt.org/
jeff at members.evolt.org
http://members.evolt.org/jeff/








More information about the thelist mailing list