How to make price 0.00 instead of 0.0?
my users can input and create prices. I wanted to know how to make it so when users input 23.5 they get 23.50 instead or 0.0 they get 0.00. How does one add to the t.decimal or my price:decimal the following ability?
Thank you for the help!
The Answer (:price with scale and precision)开发者_开发百科
class CreatePrices < ActiveRecord::Migration
def self.up
create_table :prices do |t|
t.string :price_name
t.decimal :price, :precision => 10, :scale => 2
t.date :date
t.timestamps
end
end
def self.down
drop_table :prices
end
end
Schema.rb:
create_table "prices", :force => true do |t|
t.string "price_name"
t.decimal "price", :precision => 10, :scale => 2
t.date "date"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
end
my scaffolded form: <%= f.label :price %> <%= f.text_field :price %>
Then in your view put number_to_currency(@model.attribute):
Price:
Try using the :scale
option in your migration. Use a scale of 2 if you want two digits to the right of the decimal point, e.g:
t.decimal :price, :precision => 10, :scale => 2
Without using precision and scale, I did it like this:
def price #in price model to set price field
number_to_currency(self[:price], :unit => '')
end
Migration as:
t.float :price, :default => '1.00'
View as:
f.text_field :price
I ended doing the scale and precision but also adding in the view the number_to_currency method.
精彩评论