# Add Comma to Total Value

I have the script below and am trying to figure out how to add a comma value for the ‘thousand’ place after the total has been calculated. Anyone know how I can accomplish this?

<script type="text/JavaScript">
function calculateCheck()
{
var op1=document.getElementsByName('form[swimclubmem1][]');
var op2=document.getElementsByName('form[swimclubmem2][]');
var result=document.getElementById('Total');

result.value=0;

result.value=parseInt(result.value);

for(i=0;i<op1.length;i++)
if(op1[i].checked) result.value=parseInt(result.value)+parseInt(op1[i].value);

for(i=0;i<op2.length;i++)
if(op2[i].checked) result.value=parseInt(result.value)+parseInt(op2[i].value);
}

</script>

Thank you.

You could run your total through a simple formatting function that would format the number for you.

I found a nice solution on StackOverflow that I’ve cleaned up a little:

/**
* Format a number
* @param Number n The number to format
* @param Number c The precision (decimal places)
* @param String d Decimal place character
* @param String t Thousand place character
*
* @return String  Formatted number
*/
function format(n, c, d, t){
var s, i, j;

c = isNaN(c = Math.abs(c)) ? 2 : c;
d = d === undefined ? "," : d;
t = t === undefined ? "." : t;

s = n < 0 ? "-" : "";
i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + "";
j = (j = i.length) > 3 ? j % 3 : 0;

return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\\d{3})(?=\\d)/g, "\$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
// call like:
// format( 12345.67, 2, ".", ",");

Thank you, AussieJohn:

Thank you for your time in cleaning up the code.

Put it to you this way, it took me days just to figure out how to accomplish the one code I have up above. To integrate the one you provided, it’ll take me more days to figure out. That’s how much of a rookie I am.