PDA

View Full Version : Splitting a Number


Eternity Angel
10-05-2002, 08:37 PM
Howdy, it's my inquisitive self again.

I am curious as to if JavaScript has a specific command to split a number like 1267618, and add commas where needed, so it would make 1,267,618?

If there ISN'T, then do you have a script that could do it? I don't think my way is that effective, since it's so bulky...


var random = 66298762343;
var random2 = "";
var random3 = String(random);
var temp = 0;
for (b=random3.length;b>=0;b--) {
if (temp >= 3) {
temp=0;
random2 = ","+random3.charAt(b)+random2;
} else {
random2 = random3.charAt(b)+random2;
}
temp++;
}
if (random2.charAt(0) == ",") {
random3 = "";
for (a=1;a<random2.length;a++) {
random3 = random3+random2.charAt(a);
}
random2 = random3;
}
alert(random2);


See? It doesn't look too good for just adding it to ONE number. Any help is greatly appreciated, since this has been annoying me for awhile (just the bulkiness of it).

adios
10-05-2002, 11:12 PM
http://www.codingforums.com/showthread.php?threadid=6949&highlight=commas

RadarBob
10-06-2002, 11:00 PM
Here's another solution. Of course not as elegant as the regular expression solution from the above link but was a fun exercise in recursion.:cool:


<html>
<title>Inserting commas into a number</title>

<head>
<script type="text/javascript">

function commaTize (theNumber) {
var thisPiece = new String();
var NewNbr = new String ();

if (theNumber.length >= 4) {
thisPiece = "," + theNumber.slice (theNumber.length-3, theNumber.length);
theNumber = theNumber.slice (0, theNumber.length-3);
NewNbr = commaTize (theNumber);
}else{
thisPiece = theNumber;
theNumber = "";
}

NewNbr = NewNbr + thisPiece;
return NewNbr;
} // commaTize ()

</script>
</head>

<body>
<script type="text/javascript">
var original = new String ("123456789");
var commaNbr = new String ();

document.write ("Here is the original number: " + original + "<BR>" );
commaNbr = commaTize(original);
document.write ("Here is the number w/ commas: " + commaNbr + "<BR>");
</script>
</body>
</html>


Man, I gotta learn RegExp's !!!:eek: