Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  136] [ 3]  / answers: 1 / hits: 114417  / 14 Years ago, thu, october 7, 2010, 12:00:00

I have these numbers



10999 and 8094 and 456



And all i want to do is add a comma in the right place if it needs it so it looks like this



10,999 and 8,094 and 456



These are all within a p tag like this <p class=points>10999</p> etc.



Can it be done?



I've attempted it here with the help of other posts http://jsfiddle.net/pdWTU/1/ but can't seem to get it to work



Thanks



Jamie



UPDATE



Messed around a bit and managed to figure it out here http://jsfiddle.net/W5jwY/1/



Going to look at the new Globalization plugin for a better way of doing it



Thanks



Jamie


More From » jquery

 Answers
68

Works on all browsers, this is all you need.


  function commaSeparateNumber(val){
while (/(d+)(d{3})/.test(val.toString())){
val = val.toString().replace(/(d+)(d{3})/, '$1'+','+'$2');
}
return val;
}

Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:


$('#elementID').html(commaSeparateNumber(1234567890));

or


$('#inputID').val(commaSeparateNumber(1234567890));

However, if you require something cleaner, with flexibility. The below code will fix decimals correctly, remove leading zeros, and can be used limitlessly. Thanks to @baacke in the comments.


  function commaSeparateNumber(val){
val = val.toString().replace(/,/g, ''); //remove existing commas first
var valRZ = val.replace(/^0+/, ''); //remove leading zeros, optional
var valSplit = valRZ.split('.'); //then separate decimals

while (/(d+)(d{3})/.test(valSplit[0].toString())){
valSplit[0] = valSplit[0].toString().replace(/(d+)(d{3})/, '$1'+','+'$2');
}

if(valSplit.length == 2){ //if there were decimals
val = valSplit[0] + "." + valSplit[1]; //add decimals back
}else{
val = valSplit[0]; }

return val;
}

And in your jQuery, use like so:


$('.your-element').each(function(){
$(this).html(commaSeparateNumber($(this).html()));
});

Here's the jsFiddle.


[#95394] Monday, October 4, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leslijessalyng

Total Points: 650
Total Questions: 85
Total Answers: 109

Location: Croatia
Member since Mon, Sep 6, 2021
3 Years ago
leslijessalyng questions
Fri, Feb 21, 20, 00:00, 4 Years ago
Tue, Jul 30, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
;