A more thorough solution
The core of this is the replace
call. So far, I don t think any of the proposed solutions handle all of the following cases:
- Integers:
1000 => 1,000
- Strings:
1000 => 1,000
- For strings:
- Preserves zeros after decimal:
10000.00 => 10,000.00
- Discards leading zeros before decimal:
01000.00 => 1,000.00
- Does not add commas after decimal:
1000.00000 => 1,000.00000
- Preserves leading
-
or +
: -1000.0000 => -1,000.000
- Returns, unmodified, strings containing non-digits:
1000k => 1000k
The following function does all of the above.
addCommas = function(input){
// If the regex doesn t match, `replace` returns the string unmodified
return (input.toString()).replace(
// Each parentheses group (or capture ) in this regex becomes an argument
// to the function; in this case, every argument after match
/^([-+]?)(0?)(d+)(.?)(d+)$/g, function(match, sign, zeros, before, decimal, after) {
// Less obtrusive than adding reverse method on all strings
var reverseString = function(string) { return string.split( ).reverse().join( ); };
// Insert commas every three characters from the right
var insertCommas = function(string) {
// Reverse, because it s easier to do things from the left
var reversed = reverseString(string);
// Add commas every three characters
var reversedWithCommas = reversed.match(/.{1,3}/g).join( , );
// Reverse again (back to normal)
return reverseString(reversedWithCommas);
};
// If there was no decimal, the last capture grabs the final digit, so
// we have to put it back together with the before substring
return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
}
);
};
You could use it in a jQuery plugin like this:
$.fn.addCommas = function() {
$(this).each(function(){
$(this).text(addCommas($(this).text()));
});
};