1

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,
Mel
  • 2,481
  • 26
  • 113
  • 273

1 Answers1

0

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

Community
  • 1
  • 1
MZaragoza
  • 10,108
  • 9
  • 71
  • 116
  • Hi, but does BigDecimal block users from entering cents or pennies? – Mel Jun 15 '15 at 04:45
  • no the opposite the BigDecimal is a Decimal so it allows you to enter the dot "." that brakes the money into the cents or pennies that is where the `:scale` comes into place *scale is the number of digits right of the decimal point* – MZaragoza Jun 15 '15 at 12:19
  • so how do i block people from entering .00? I want them to enter 100 and for it to mean $100 – Mel Jun 15 '15 at 12:20
  • 1
    for **$100**, they would enter **100** and for **$100.50** they would enter **100.50** they dont need to put the dot unless they want to enter cents – MZaragoza Jun 15 '15 at 12:22