views:

26

answers:

2

I want to store currencies in my (sqlite and mysql) databases. I'm trying to use the decimal column type, with :scale => 2.

This isn't behaving as expected. If I save a record with :rate => 10.50, it is stored in my sqlite db as 10.5. In addition, when I output the value in a form field, it is displayed as 10.5.

I don't want to do hacky string formatting every time I want to display values nicely in Rails forms.

Is there a way to get around this? Is it an sqlite thing? Do I just misunderstand the decimal column type?

Edit:

To clarify, I want to be able so use the usual form generation methods:

- form_for @project do |f|
  = f.text_field :rate

If I have to explicitly format the output, I'll have to create extra methods for every decimal attribute:

def formatted_rate
  "%.2f" % rate
end

= f.text_field :formatted_rate

Are there any other common tricks to force the output formatting, and still use the default Rails formbuilder?

+1  A: 

You can use the Rails ActionView Number Helper number_with_precision:

number_with_precision(my_number, :precision => 2)
Tim
This won't help me to nicely output the value in a form field
nfm
There is also a "number_to_currency" method
Tim
@nfm `<%= f.text_field :rate, :value => number_with_precision(f.object.rate) %>`
meagar
A: 

I ended up writing a plugin to do this: currency_text_field.

You can define your formats (arguments to number_with_precision) in config/initializers/currency_text_field_initializer.rb.

Then you use f.currency_text_field :rate in your form, with an optional :format argument to use a named format in the initializer. Otherwise it uses the format[:default] from the initializer.

Same approach as setting the value explicitly, but does it all behind the scenes and has named sets of options to number_with_precision.

nfm