Results 1 to 3 of 3

Thread: Format Numbers in Javascript

  1. #1

    Thread Starter
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Format Numbers in Javascript

    hi all ,

    I need a little help on a script...

    I have a number from 0 to 300.
    What I want to do is format them to like 030, 004, or 250.
    I've tried to use string.length and stuff to put those extra zero's in front, but I can't get it to work...

    Anyone?

    thnx in advance

  2. #2
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: Format Numbers in Javascript

    I can't remember now if JavaScript used switch like PHP does, so just an IF structure here:
    Code:
    function padlen(numstr) {
        if(numstr.length > 2) return numstr;
        if(numstr.length == 2) return '0' + numstr;
        if(numstr.length == 1) return '00' + numstr;
        return '000';
    }
    And untested, of course.

  3. #3

    Thread Starter
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: Format Numbers in Javascript

    thnx for the reply but the function only seems to return 000

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width