PDA

View Full Version : Add commas to a numeric value



mburt
07-22-2006, 04:29 PM
Hi,
I'm wondering how you would add commas to a number, say, in an <input> tag.
Ex.
1
12
123
1,234
12,345
123,456
1,234,567

I really want to know how to do this! I've seen similar scripts, but it is very confusing. Thank-you.

Twey
07-22-2006, 10:36 PM
Number.prototype.withThousandsSeparator = function(sep) {
var s = this.toString(),
y = (s.indexOf(".") > -1 ? s.substring(s.indexOf(".")) : "");
if(y) s = s.substring(0, s.indexOf("."));
for(var i = s.length - 3;i > 0;i -= 3) {
var front = s.substring(0, i),
back = s.substring(i);
s = front + sep + back;
}
return s + y;
}

mburt
07-22-2006, 11:45 PM
How do I access this function?

Twey
07-22-2006, 11:55 PM
var num = 1234567;
window.alert(num.withThousandsSeparator(','));

mburt
07-23-2006, 12:04 AM
;) Wow you're good