Rails - Format number as currency format in the Getter

Posted by daemonsy on Stack Overflow See other posts from Stack Overflow or by daemonsy
Published on 2012-04-07T11:13:03Z Indexed on 2012/04/07 11:29 UTC
Read the original article Hit count: 266

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about currency