drmwndr
drmwndr

Reputation: 94

Rails wont return decimals correctly

I'm using Rails 3.2.5 and when it return a value o :price for editing it just brings one decimal, eg. 600.0, i need that i bring 2 decimals (eg. 600.00) in database is recorded 600.00, in my locales i already set for 2 decimals, and still dont work.

I tried

number_to_currency(:price, :precision => 2) 

but it works well for a view like "show", i need that it return the propper value for editing, on textfield.

in my migration the field "price" is set do decimal(15,2).

Can someone help?

Thank You!

Upvotes: 0

Views: 286

Answers (4)

drmwndr
drmwndr

Reputation: 94

Issue solved using 'delocalize' gem. Old but gold! :) Thank you all!

Upvotes: 1

Mark Westling
Mark Westling

Reputation: 5974

The simplest way to have your text_field display a formatted value is to pass it explicitly, like this:

f.text_field :price, :value => number_to_currency(:price, :precision => 2) 

You'll need to interpret (and possibly re-format) the value in the controller method that handles the form.

See How can I format the value shown in a Rails edit field?

Upvotes: 0

Ylan S
Ylan S

Reputation: 1786

In my experience, instead of using decimal for storing currency, it's best to store the amounts in cents, as an integer. This will take care of multiple problems, including the one you are having now.

I have had much success in the past using the Money gem and its companion money-rails.

Upvotes: 1

Larry K
Larry K

Reputation: 49104

The text fields are operating on the "native" value of the field, as it is handled by ActiveRecord, not as it is stored in the database.

Currency fields are tricky since ActiveRecord is translating between the database representation and the ruby/rails representation, a BigDecimal.

If your goal is that you want to show your users $1,000.00 and enable them to edit it, some ideas:

  1. Use the Money gem Ylan S refers to.
  2. Use an Edit in place widget Eg screencast. You'd use number_to_currency to display the value. When clicked, the input field would show the value without the currency symbol, commas for thousands separators, etc. Note that this is how Excel works: when you edit the value of a currency field, you don't enter 1,000. You enter 1000.

Upvotes: 3

Related Questions