Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 9 of 9
  1. #1
    New Coder
    Join Date
    Aug 2003
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    how to format a number with thousand seperators?

    Hi all,

    Is it possible using a regular expression / pattern matching/replacemenet (or the Math object ?) to format a number like this:

    Format this :
    -22313256

    to this:

    -22,313,256.00

    Now, we came up with this:
    >>> Function >>>>>


    function formatthousands (number, precision){
    var finalstring, tnumber, buffer;
    var flag;
    if(number<0) {
    flag="-";
    number=Math.abs(number) ;
    }else
    {
    flag="";
    }
    finalstring=new String();
    var decimal = number%1;
    var integer = number-decimal;
    decimal=number-integer;
    while (integer > 0){
    tnumber = integer/1000;
    buffer=Math.round(1000*(tnumber-Math.floor(tnumber)))
    finalstring=buffer.toString()+","+finalstring;
    // WScript.Echo(finalstring);
    integer=tnumber-(tnumber%1);
    }
    finalstring=finalstring.substring(0,finalstring.length-1);

    if (precision!=0)
    {
    if (decimal==0)
    {
    decimal = "0.0000000000000000001"
    }
    finalstring=finalstring+"."+decimal.toString().substr(2).substr(0,precision);
    }
    return (flag+finalstring);
    };

    //WScript.Echo(formatthousands (-124656.001,0))

    <<<<< END <<<<

    but can it be done with a one-line regular expression?

    If so, can u help me please?

    thanks

    Philip
    Last edited by deadstone; 10-15-2003 at 05:33 PM.

  • #2
    Regular Coder
    Join Date
    Aug 2003
    Location
    Loughborough University
    Posts
    427
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I don't think this is a one liner, but I have got a considerably shorter version if you're interested:
    Attached Files Attached Files
    AMD Athlon "Barton" XP 3200+ (11*200.5MHz = 2.2GHz)
    BFG GeForce 6800 Ultra OC 256Mb
    3 * Kingston 256Mb PC3200 DDR400
    Seagate Barracuda 120Gb Ultra ATA-100 and Seagate Barracuda 160Gb, SATA-150

  • #3
    Senior Coder joh6nn's Avatar
    Join Date
    Jun 2002
    Location
    72° W. 48' 57" , 41° N. 32' 04"
    Posts
    1,887
    Thanks
    0
    Thanked 1 Time in 1 Post
    we had a challenge involving that a while back, actually. http://www.codingforums.com/showthre...threadid=13577

    if i weren't a lazy jerk, i would actually combine aspects of all the solutions that were presented in the challenge, but i AM a lazy jerk, and as such, i only just corrected the bugs i found in my code.

    i haven't looked at lavalamp's code, but i would suggest looking at everyone's code, and then deciding what works best for you. or, if you're motivated enough, you might even do what i should have, and try to combine the best elements of everyone's solution.
    bluemood | devedge | devmo | MS Dev Library | WebMonkey | the Guide

    i am a loser geek, crazy with an evil streak,
    yes i do believe there is a violent thing inside of me.

  • #4
    Regular Coder
    Join Date
    Jul 2003
    Location
    NJ - #29 if you must know
    Posts
    117
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Below are the functions I use

    function removecomma(numb) {
    var temporary="";
    for (var i=0;i < numb.length;++i) {
    var c=numb.charAt(i);
    if (c!=",") {temporary += c;}
    }
    return temporary;
    }

    function putcomma(numb,noplace) {
    var temporary = "";
    var cplace = 0 ;
    var decn=numb-makeint(numb);
    decn=decn * (Math.pow(10,noplace));
    decn=Math.round(decn);
    decn=Math.abs(decn);
    decn=padit(decn,noplace);
    var wholen=makeint(numb)+"";
    var ii=wholen.length-1;
    for (var i=ii;i > -1;i=i-1) {
    var c=wholen.charAt(i)+"";
    if (c != "-") {
    if (cplace == 3) {
    temporary = "," + temporary + "" ;
    cplace = 0 ;
    }
    temporary = c + temporary + "" ;
    cplace = cplace + 1 ;
    } else {
    temporary = c + temporary + "" ;
    }
    }
    temporary = temporary + "." + decn + "";
    return temporary;
    }

  • #5
    Regular Coder
    Join Date
    Jul 2003
    Location
    NJ - #29 if you must know
    Posts
    117
    Thanks
    0
    Thanked 0 Times in 0 Posts
    oops forgot these two

    function padit(numb,nlen) {
    var str="" + numb ;
    while (str.length < nlen) {
    str=str+"0";
    }
    return str;
    }

    function makeint(numb) {
    if (numb < 0) {
    return Math.ceil(numb);
    } else {
    return Math.floor(numb);
    }
    }

  • #6
    New Coder
    Join Date
    Aug 2003
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    thanks everyone

    for these excellent suggestions...

    We also found out that we can call a VB function from JavaScript and do it in a kind of roundabout way with only one or 2 lines of code!

    cheers

    Philip

  • #7
    New Coder
    Join Date
    Aug 2003
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    The best yet!

    Hi all,

    this guy LeRexus posted this in answer to another desparate post of mine:

    http://www.codingforums.com/showthre...990#post142990

    <script>
    function formatNumber(num,spl){
    return num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/img,'$1,').split('').reverse().join('');
    }

    alert(formatNumber(1234567.89));
    </script>
    maybe that's all it takes!

    cheers

    Philip

  • #8
    New Coder
    Join Date
    Aug 2002
    Location
    Oakland, CA
    Posts
    45
    Thanks
    1
    Thanked 0 Times in 0 Posts

    bug and fix for regexp solution

    Thanks for posting here deadstone. Your regexp turned out to be a jump start on a quick fix. I found one error with the regexp and added a feature, many may find useful.

    My js needed to list monetary values, in which case the decimal portion required padding if (present). My addition doesn't *add* a decimal portion if it wasn't there, but it does add a 0 (zero) if a single-digit decimal exists.

    I added the following to the end of the statement:

    .replace(/\d(\.\d)\b/mg,'$1Z').replace(/(Z)\b/mg,'0')

    This is not the best line in the world, but it's the only way I could add a number after using a back-reference. I add a capital "Z" and then replace that with a zero. It's ugly but it works, and know that any trailing "Z"s may be replaced with a zero.

    Then I noticed a bug in the original statement... if the number already has a single-digit decimal the commas are placed incorrectly. So, I placed the above code, *before* the comma-inserting-code... sorta like a fixed to numbers with single-digit decimals.

    Nevertheless, below is the entire statement which pads a zero and inserts commas into numeric values.

    num = num.toString().replace(/\d(\.\d)$/mg,'$1Z').replace(/(Z)$/mg,'0').split('').reverse().join('').replace(/(?=\d\.?)(\d{3})(?=\d)/mg,'$1,$2').split('').reverse().join('').replace(/\d(\.\d)$/mg,'$1Z').replace(/(Z)$/mg,'0');

    Enjoy, and if anyone has a way of getting around the double-replacement style of padding numerics, please post!

    - Best O'Luck!

  • #9
    Regular Coder
    Join Date
    Dec 2002
    Posts
    169
    Thanks
    0
    Thanked 0 Times in 0 Posts

    getting around the double-replacement

    Quote Originally Posted by rawsweets
    Thanks for posting here deadstone. Your regexp turned out to be a jump start on a quick fix. I found one error with the regexp and added a feature, many may find useful.

    My js needed to list monetary values, in which case the decimal portion required padding if (present). My addition doesn't *add* a decimal portion if it wasn't there, but it does add a 0 (zero) if a single-digit decimal exists.

    I added the following to the end of the statement:

    .replace(/\d(\.\d)\b/mg,'$1Z').replace(/(Z)\b/mg,'0')

    This is not the best line in the world, but it's the only way I could add a number after using a back-reference. I add a capital "Z" and then replace that with a zero. It's ugly but it works, and know that any trailing "Z"s may be replaced with a zero.

    Then I noticed a bug in the original statement... if the number already has a single-digit decimal the commas are placed incorrectly. So, I placed the above code, *before* the comma-inserting-code... sorta like a fixed to numbers with single-digit decimals.

    Nevertheless, below is the entire statement which pads a zero and inserts commas into numeric values.

    num = num.toString().replace(/\d(\.\d)$/mg,'$1Z').replace(/(Z)$/mg,'0').split('').reverse().join('').replace(/(?=\d\.?)(\d{3})(?=\d)/mg,'$1,$2').split('').reverse().join('').replace(/\d(\.\d)$/mg,'$1Z').replace(/(Z)$/mg,'0');

    Enjoy, and if anyone has a way of getting around the double-replacement style of padding numerics, please post!

    - Best O'Luck!
    How about...

    Code:
    function punctuated(n){
      var s=(''+n).split('.');
      s[0]=s[0].split('').reverse().join('').match(/\d{1,3}/gi).join(',').split('').reverse().join('');
      return(s.join('.'));
    }
    First, this splits the number (forced to be a string) around the decimal point (if any). Second, it reverses the integer portion (split/reverse/join), matches up to three digits (regular expression's standard greedy algorithm), joins these trios with commas, and unreverses the punctuated integer (split/reverse/join). Finally, it returns the whole puncuated number including original decimal portion.

    Enjoy!


  •  

    Posting Permissions

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