Rails - Format number as currency format in the Getter
currency, ruby-on-rails
Solution
Just add a method in your model which is named like your attribute in the database like:
def price
"$%.2f" % self[:price]
end
which gives you full control over the formatting or use the Rails provided helper method
def price
ActionController::Base.helpers.number_to_currency(self[:price])
end
this should do the trick. hope it helps!
Problem
I am making a simple retail commerce solution, where there are prices in a few different models. These prices contribute to a total price. Imagine paying $0.30 more for selecting a topping for your yogurt. When I set the `price` field to ``` t.decimal :price, precision:8, scale:2 ``` The database stores `6.50` as `6.5`. I know in the standard rails way, you call `number_to_currency(price)` to get the formatted value in the Views. I need to programmatically call the `price` field as well formatted string, i.e. $6.50 a few places that are not directly part of the View. Also, my needs are simple (no currency conversion etc), I prefer to have the price formatted universally in the model without repeated calling number_to_currency in views. Is there a good way I can modify my getter for price such that it always returns two decimal place with a dollar sign, i.e. $6.50 when it's called? Thanks in advance. UPDATE Thanks everyone. I've elected to use Alex's approach because it seems very 'hackish' to do the includes just for formatting the number. Using his approach, I did: ``` def price_change=(val) write_attribute :price_change, val.to_s.gsub(/[\$]/,'').to_d end def price_change "$%.2f" % self[:price_change] end ``` Cheers. UPDATE 2 Caveat Emptor. Once you do this, you lose the ability to do operations to the number because it's now a string. Please beware if anyone is facing the same problem as me.