Adding commas to numbers
I could not find any good utils out there to add commas to numbers in JavaScript. So I wrote one:
This file contains 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
<script type="text/javascript"> | |
function comma(num) { | |
var collector = new Array(); | |
var numberArray = ('' + num).split('').reverse(); | |
for(var i = 0; i < numberArray.length; i++) { | |
if(i % 3 == 0 && i != 0) collector.push(","); | |
collector.push(numberArray[i]); | |
} | |
return collector.reverse().join(''); | |
} | |
</script> |
I found a Ruby example a long time ago, and it has served me well. Here is my Ruby comma util:
This file contains 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
class Numeric | |
# Usage: 1234.commify # => '1,234' | |
def commify | |
self.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(',').reverse | |
end | |
end |
I love the Ruby version, but I am pretty proud of my JavaScript version as well.
No comments:
Post a Comment