Click to See Complete Forum and Search --> : Formatting results of a calculation


Combustion
07-06-2004, 12:10 PM
I have a question which has had me stumped for a few days now. I have a form that I add the values of fields together and display the total in a total field. I have the calculations working correctly. My problem is that I would like to change the format of the total from 1234567 to 1,234,567 . Is this possible using javascript? Here is the code that I use to do the calculations. I have edited out all the code that I use to validate the fields because I don't think it is needed for this question.

Thanks in advance.


function calculateTotal(){
var fields=Array("life1","life2","life3","life4","life5","life6");
for(i=0;i<fields.length;i++){
str="var val"+i+"=parseInt(document.frmLifeNeed."+fields[i]+".value);";
eval(str);
}
total=val0+val1+val2+val3+val4-val5
document.frmLifeNeed.total.value = total;
}

Charles
07-06-2004, 01:55 PM
<script type="text/javascript">
<!--

String.prototype.reverse = function () {return this.split('').reverse().join('')};

Number.prototype.withCommas = function () {
if (isNaN (this)) return NaN.toString();
var l = Math.floor(Math.abs(this)).toString();
var r = Math.round((Math.abs(this) % 1) * 100).toString();
return [(this < 0 ? '-' : ''), (l.length > 4 ? l.reverse().match(/\d{1,3}/g).join(',').reverse() : l),'.', (r < 10 ? '0' + r : r)].join('').replace(/0+$/, '').replace(/\.$/, '');
}

i = -1234567890
alert(i.withCommas())
// -->
</script>

Charles
07-06-2004, 02:11 PM
Or perhaps...

<script type="text/javascript">
<!--

String.prototype.reverse = function () {return this.split('').reverse().join('')}

function Integer (n) {this.n = typeof n == 'number' ? Math.floor(n) : parseInt(n)}

Integer.prototype.valueOf = function () {return this.n}

Integer.prototype.toString = function () {return [(this.ammount < 0 ? '-' : ''), (this.n.toString().length > 4 ? this.n.toString().reverse().match(/\d{1,3}/g).join(',').reverse() : this.n.toString())].join('')}

alert (new Integer(1234567.89))
// -->
</script>