Link to home
Start Free TrialLog in
Avatar of rmassart
rmassart

asked on

Converting 1000 to 1,000

I would like to create a regular expression which will add the commas to between every "thousand" of a number. eg will convert 1234567.89 to 1,234,567.89. It should work for negative as well as positive numbers.

Thanks,
Robin
Avatar of cheekycj
cheekycj
Flag of United States of America image

try this:
<script language="JavaScript"><!--
function outputComma(number) {
    number = '' + number
    if (number.length > 3) {
        var mod = number.length%3;
        var output = (mod > 0 ? (number.substring(0,mod)) : '');
        for (i=0 ; i < Math.floor(number.length/3) ; i++) {
            if ((mod ==0) && (i ==0))
                output+= number.substring(mod+3*i,mod+3*i+3);
            else
                output+= ',' + number.substring(mod+3*i,mod+3*i+3);
        }
        return (output);
    }
    else return number;
}

from irt.com

CJ
Avatar of rmassart
rmassart

ASKER

Thanks,

But I was really looking for a regular expression which would do this, rather than a function.

Robin
Does this shed any light on it:
http://www.asptoday.com/articles/20000328.htm

CJ
Hi rmassart,
Here's a solution using the RegExp object.
I dunno why, but the "g" doesn't seem to work as I'd expect to, so a while loop is necessary.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
     <title>Untitled</title>
     
     <script language="javascript">

          function inscommas(snum){
               var myRegExp = new RegExp("(\\d+)(\\d{3})", "g");
               var csnum = snum, csnum2 = "";
               while (true){
                    csnum = csnum.replace(myRegExp , "$1,$2");
                    if (csnum == csnum2) break;
                    csnum2 = csnum;
               }
               return csnum;
          }

     </script>
</head>

<body>
<input type="text" name="ntext">
<br>
<input type="button" value="insert commas" onclick="alert(inscommas(ntext.value))">
</body>
</html>
I had almost forgotten about this question. Nice try, but it doesn't work with numbers which have more than 3 decimal places, since it puts in the commas after the dot as well, which it shouldn't. eg 123456.7891 goes to 123,456.7,891

Robin
ASKER CERTIFIED SOLUTION
Avatar of rondi
rondi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks,
Robin