add commas to a number in jQuery
Solution 1
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.
Solution 2
Number(10000).toLocaleString('en'); // "10,000"
Solution 3
Timothy Pirez answer was very correct but if you need to replace the numbers with commas Immediately as user types in textfield, u might want to use the Keyup function.
$('#textfield').live('keyup', function (event) {
var value=$('#textfield').val();
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var newvalue=value.replace(/,/g, '');
var valuewithcomma=Number(newvalue).toLocaleString('en');
$('#textfield').val(valuewithcomma);
});
<form><input type="text" id="textfield" ></form>
Solution 4
Take a look at Numeral.js. It can format numbers, currency, percentages and has support for localization.
Solution 5
function delimitNumbers(str) {
return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
});
}
alert(delimitNumbers(1234567890));
Comments
-
Jamie Taylor about 3 years
I have these numbers
10999
and8094
and456
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
and8,094
and456
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
-
ahgood over 10 yearsThis is the most simple solution and it work perfect for me. Thank you!
-
linqu over 10 yearsthank you for that hint, much better than writing custom functions or including a plugin. for me answer #1!
-
Pyrolistical over 10 yearsuser1655655's answer is way better
-
Luke over 10 yearsThis is great, and works in most desktop browsers, but beware it's limited support in mobile browsers right now... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
baacke over 10 yearsTwo issues with this answer: 1. Calling the function more than once with the same value will result in commas in the wrong places (for example, keyup events). 2. This function does not handle decimals properly and will add commas inside the decimals. See this JSFiddle for a modified version that fixes both.
-
Timothy Perez about 10 years@baacke The idea of this function is to be slim, so I didn't account for calling it twice on a the same var or decimals (since it wasn't in the question). Either way, your fiddle example is useful for cases where you would need a decimal so thank you.
-
Tom Spencer over 9 yearsFor anybody looking to use this with Node.js, it won't work unless you re-compile the v8 engine to include i18n: stackoverflow.com/questions/23571043/…
-
Aamir Afridi about 9 yearsTry this
Number(012).toLocaleString('en')
:| -
Fillip Peyton about 9 yearsClever technique if number doesn't have a leading zero and browser support doesn't precede IE11.
-
Isaac Askew about 9 yearsThis is inconsistent across browsers and doesn't work at all on iPad.
-
Alex Harvey almost 9 yearsWhere a comma or period appears is determined by locale. The JS standard library can already do this for you. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
Venryx about 7 years@FillipPeyton If you're worried about the leading-zero case, just do
Number("012").toLocaleString("en");
(in other words, provide the number as a string rather than a number literal -- which is how you'd usually use it anyway) -
Venryx about 7 yearsNote that if the number has a decimal portion, this approach will trim the decimal portion to only the first 3 digits. If you want to keep the decimal portion untouched, split it into the integer and fractional parts, and only change the integer part. Example: jsfiddle.net/tqb4x8dp
-
Murtaza JAFARI about 3 yearsThe best solution without doing custom things