jQuery plugin to add comma separating numbers into three digits without white spaces and if total digits are under three, then no comma added.
Ex. 2984 => 2,984 and 297312984 => 297,312,984 and 298 => 298
$('span.rawNums').digits();
Thanks.
jQuery plugin to add comma separating numbers into three digits without white spaces and if total digits are under three, then no comma added.
Ex. 2984 => 2,984 and 297312984 => 297,312,984 and 298 => 298
$('span.rawNums').digits();
Thanks.
You could try NumberFormatter.
$(this).format({format:"#,###.00", locale:"us"});
It also supports different locales, including of course US.
Here's a very simplified example of how to use it:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.numberformatter.js"></script>
<script>
$(document).ready(function() {
$(".numbers").each(function() {
$(this).format({format:"#,###", locale:"us"});
});
});
</script>
</head>
<body>
<div class="numbers">1000</div>
<div class="numbers">2000000</div>
</body>
</html>
Output:
1,000
2,000,000
You can also look at the jquery FormatCurrency plugin, it has support for multiple locales as well, but may have the overhead of the currency support that you don't need.
$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });
This is not jQuery, but it works for me. (I did not write this, but I do not recall where I got it.)
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Something like this if you're into regex, not sure of the exact syntax for the replace tho!
MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
@Paul Creasey had the simplest solution as the regex, but here it is as a simple jQuery plugin:
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
})
}
You could then use it like this:
$("span.numbers").digits();