Formatting US dollars with Ruby
This was surprisingly hard to find, so I thought I would post it here. This line will format a number as US dollars, including commas. In a Rails view, you can just use number_to_currency, but in straight-up Ruby, you can do this:
sprintf('$%0.2f',value).gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,")
Just another reminder for me that I need to brush up on regular expressions.


Mike,
That’s perfect. I was looking for this very thing for a camping app I’m writing. It’s such a simple thing, but I just didn’t take the time to track it down. I just purchased Mastering Regular Expressions, but have yet to read much more than the preface.
Thanks.
Josh