Rails Money gem - block users from entering cents/pennies/subunits

376 views Asked by At

I'm using money-rails with my Rails 4 app.

I display my monetized attributes without cents. I'd like users to enter whole dollar/pound amounts only (so instead of 100 being $1, I'd like it to be $100).

In my form, I ask users:

        <%= par.input :participation_cost_pennies, label: false, placeholder: 'Whole numbers only', :input_html => {:style => 'width: 250px; margin-top: 20px', class: 'response-project'} %>

In my show, I have:

   <%= money_without_cents_and_with_symbol @project.scope.participant.participation_cost  %>

I'd like to know how to either add .00 to whatever gets entered by the user in the form, or preferably, to make the entered value a dollar amount rather than a cents amount. Does anyone know how to do that?

I have removed cents in my money.rb initialiser:

config.default_format = {
     :no_cents_if_whole => nil,
1

There are 1 answers

4
MZaragoza On

When working with money I like to use DECIMAL instead of INTEGERS in my database.

In your migration, do something like this:

add_column :items, :price, :decimal, :precision => 8, :scale => 2
# precision is the total amount of digits
# scale is the number of digits right of the decimal point

In Rails, the :decimal type is returned as BigDecimal, which is great for price calculation.

If you insist on using integers, you will have to manually convert to and from BigDecimals everywhere.

to print the price, use:

number_to_currency(price, :unit => "$")
#=> $1,234.01

look at http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency

https://stackoverflow.com/a/1019972/1380867