Created
March 3, 2011 04:17
-
-
Save jdsharp/852326 to your computer and use it in GitHub Desktop.
Quick and dirty code to insert commas after every 3 digits (also handles decimals correctly)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// via @DmitryBaranovsk | |
function dirtyCommas(num) { | |
return String(num).replace(/^\d+(?=\.|$)/, function (int) { return int.replace(/(?=(?:\d{3})+$)(?!^)/g, ","); }); | |
} |
I just applied jdalton's 2011.03.04 version to something I'm working on and found that I'll need a way to make it skip over dates. Example confusion: "...vol. 1, no. 4, pp. 4-9, July/August 1,995, concluded that..." (should contain "August 1995", rather than implying the nonsensical "July through August 1st, 995"). Guess I have my work cut out for me.
I've been trying several versions of this and it works great with numbers that are not thousand rounded.
for instance, 1234 goes 1,234.00.
But when I have 4000, I get a 4,0.00, so it basically removes 3 zeros off the thousands portion.
Does anyone have a clue?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ok so the thing I could come up with is:
String(value).replace(/(\.\d+)|(?=(?:\d{3})+\b)(?!\b)/g, function(m, $1) { return $1 || ',' });
It requires passing a function but still just 1 regexp.