I’m working on a small application in which currency – specifically USD – will be stored in a MySQL database.

Because Rails supports a variety of number formats, it’s not completely obvious which is the best to use when storing monetary values.

Using a decimal with a certain level of precision seems to be the most scalable option.

add_column :item, :price, :decimal, :precision => 8, :scale => 2

Here, I’m adding a price column with the type of decimal to the item table. The precision value is somewhat arbitrary as it’s based on the total number of digits your field will support. The scale attribute is the number of digits that will be available to the right of the decimal points.

Finally, Rails’ number_to_currency helper works will with this particular column type for easily formatting data in the view.


    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.