Click to See Complete Forum and Search --> : question re: script to add commas to numbers


BrainDonor
06-10-2003, 01:14 PM
I found some code on this site and tweaked it a bit so add commas to numbers that I pass to the function. Can anyone tell me why this doesn't work? I know the function is receiving numbers because I had built in an alert to be sure.

Chart.prototype.getComma = function(r) {

var w = r.split("").reverse().join("");

var q = "";
for (var i=0; i<w.length; i++) {
q += w.charAt(i);
if ((i + 1) % 3 == 0 && i+1 != w.length) {
q += ",";
}
}

q = q.split("").reverse().join("");
return q
}

This does work when I change the r.split("").reverse().join(""); to "123456789".split("").reverse().join(""); but it returns the #'s 1-9 as I have them hard-coded in. Why won't the variable approach work here?

Thanks in advance.

Tom

amdRocks
06-10-2003, 01:29 PM
I saw you posted this question few times...Offer some money man...I am sure some of the volunteers will spend some time on your problem..:-)

BrainDonor
06-10-2003, 01:32 PM
Well, I did have a similar post (had more to do with graphs though), but decided to head down that road myself...then I hit this speed-bump. Besides, this isn't for my personal use...it's for my company. I don't think that my offering their money to people would be appreciated. :)

Tom

Charles
06-10-2003, 01:56 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('');
}

alert (Number(12345.65).withCommas());
// -->
</script>

BrainDonor
06-10-2003, 06:13 PM
Well, here's how it ended up...


Chart.prototype.getComma = function(r) {

var l = Math.floor(Math.abs(r)).toString();
l = l.split("").reverse().join("");

var q = "";
for (var i=0; i<l.length; i++) {
q += l.charAt(i);
if ((i + 1) % 3 == 0 && i+1 != l.length)
{q += ",";}
}

q = q.split("").reverse().join("");
return q
}

Thanks for your help guys...it is appreciated. :D

Tom