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. 🙂


One thought on “Formatting US dollars with Ruby

  1. 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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s