Add comma to numbers every three digits
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
@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();
You could use Number.toLocaleString()
:
var number = 1557564534;
document.body.innerHTML = number.toLocaleString();
// 1,557,564,534
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,");