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
Thanks,
Robin
ASKER
Thanks,
But I was really looking for a regular expression which would do this, rather than a function.
Robin
But I was really looking for a regular expression which would do this, rather than a function.
Robin
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(n text.value ))">
</body>
</html>
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(n
</body>
</html>
ASKER
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
Robin
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks,
Robin
Robin
<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
if ((mod ==0) && (i ==0))
output+= number.substring(mod+3*i,m
else
output+= ',' + number.substring(mod+3*i,m
}
return (output);
}
else return number;
}
from irt.com
CJ