Sunday, August 23, 2009

Adding commas to numbers

I could not find any good utils out there to add commas to numbers in JavaScript. So I wrote one:

<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:

class Numeric
# Usage: 1234.commify # => '1,234'
def commify
self.to_s.reverse.scan(/(?:\d*\.)?\d{1,3}-?/).join(',').reverse
end
end
view raw commify-ruby.rb hosted with ❤ by GitHub


I love the Ruby version, but I am pretty proud of my JavaScript version as well.

No comments: