#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2002
    Location
    Seoul - Korea
    Posts
    213
    Rep Power
    12

    Smile formatted number output with JavaScript


    I want to display a number value (such as 1234567) in the form, 1,234,567. How can I do it?
    Thanks in advance.
  2. #2
  3. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Oct 2001
    Location
    New Zealand
    Posts
    1,774
    Rep Power
    24
    Took some effort, but:

    Code:
    <html>
    <head>
    <script type='text/javascript'>
    function validate() {
    text = ""
    str = document.forms[0].elements[0].value
    for (i = 0; i <= str.length; i++) {
    	text = str.substring(i, i+1) + text
    }
    count = 0
    for (i = 3; i <= str.length; i = i + 3) {
    	text = text.substring(0, i + count) + "," + text.substring(i + count,text.length);
    	count++
    }
    str = text
    text = ""
    for (i = 0; i <= str.length; i++) {
    	text = str.substring(i, i+1) + text
    }
    document.forms[0].elements[0].value = text
    }
    </script>
    </head>
    <body>
    <form>
    <textarea name='nothing'>
    </textarea>
    <input type='button' value='validate' onClick='validate()'>
    </form>
    </body>
    </html>
    There you have it!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2001
    Posts
    765
    Rep Power
    13
    <html>
    <head>
    <title>untitled</title>
    <script type="text/javascript">

    //// put this anywhere ////
    String.prototype.format = function(decplaces) {
    var n, i = 0, retStr = '', s = this.split('.');
    var rt = null, lt = s[0];
    var lgt = lt.length;
    if (s.length > 1) rt = s[1].substring(0, (decplaces || s[1].length));
    while (n = lt.charAt(i++))
    if ((lgt-i) && (lgt-i) % 3 == 0) retStr += n + ',';
    else retStr += n;
    return retStr + ((rt) ? '.' + rt : '');
    }
    ///////////////////////////

    </script>
    </head>
    <body>
    <script type="text/javascript">
    var x = '1234567';
    document.write(x.format());
    document.write('<br />');
    x = '3756.4088';
    document.write(x.format(2));
    document.write('<br />');
    x = '905095004877596.22';
    document.write(x.format());
    </script>
    </body>
    </html>
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2002
    Location
    Seoul - Korea
    Posts
    213
    Rep Power
    12

    Smile


    Thanks, all of you.

IMN logo majestic logo threadwatch logo seochat tools logo