<script language="JavaScript" type="text/javascript"><!--
/*
 *This JavaScript takes an input number and adds commas in the proper places.
 *As needed by its original purpose, also adds a dollar.
 *Copyright 1998, David Turley <dturley@pobox.com>
 *Feel free to use and build on this code as long as you include this notice.
 *Last Modified March 3, 1998
*/

function commify() {
    var Num = document.form.input.value;
    var newNum = "";
    var newNum2 = "";
    var count = 0;
    
    //check for decimal number
    if (Num.indexOf('.') != -1){  //number ends with a decimal point
        if (Num.indexOf('.') == Num.length-1){
            Num += "00";
        }
        if (Num.indexOf('.') == Num.length-2){ //number ends with a single digit
            Num += "0";
        }
        
        var a = Num.split("."); 
        Num = a[0];   //the part we will commify
        var end = a[1] //the decimal place we will ignore and add back later
    }
    else {var end = "00";}  
 
    //this loop actually adds the commas   
    for (var k = Num.length-1; k >= 0; k--){
      var oneChar = Num.charAt(k);
      if (count == 3){
        newNum += ",";
        newNum += oneChar;
        count = 1;
        continue;
      }
      else {
        newNum += oneChar;
        count ++;
      }
   }  //but now the string is reversed!
   
  //re-reverse the string
  for (var k = newNum.length-1; k >= 0; k--){
      var oneChar = newNum.charAt(k);
      newNum2 += oneChar;
  }
   
   // add dollar sign and decimal ending from above
   newNum2 = "$" + newNum2 + "." + end;
   document.form.newValue.value = newNum2;
}
// --></script>
<div align="center"><h1>Adding Commas to Numeric Entries</h1></div>
<p>This JavaScript adds commas in the proper places. The script was originally developed to convert data in the format <i>nnnn</i>, <i>nnnn.</i>, or <i>nnnn.nn</i> into a proper currency (US) amount, so it also adds a dollar sign to the front.</p>
<form name=form>
<div align="center"><table align="center">
<tr>
<td align="right">Enter a number to convert:</td>
<td><input type="text" name="input"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" name="button" value="Add Commas" onClick="commify()"></td>
</tr>
<tr>
<td align="right">Here is the converted number:</td>
<td><input type="text" name="newValue"></td>
</tr>
</table></div>
</form>
