如何使价格0.00而不是0.0?

时间:2011-06-05 18:37:46

标签: ruby-on-rails

我的用户可以输入和创建价格。我想知道怎么做才能当用户输入23.5时他们得到23.50而不是0.0他们得到0.00。如何添加到t.decimal或我的价格:十进制以下能力?

感谢您的帮助!

答案(:具有规模和精确度的价格)

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

我的脚手架形式:   的     &lt;%= f.label:price%&gt;
    &lt;%= f.text_field:price%&gt;   

然后在你的视图中输入number_to_currency(@ model.attribute):

  价格:   

3 个答案:

答案 0 :(得分:5)

尝试在迁移中使用:scale选项。如果您想要小数点右边的两位数,请使用2的刻度,例如:

 t.decimal :price, :precision => 10, :scale => 2

答案 1 :(得分:4)

不使用精度和比例,我这样做了:

def price #in price model to set price field
 number_to_currency(self[:price], :unit => '')
end

迁移为:

t.float :price, :default => '1.00'

查看方式:

f.text_field :price

答案 2 :(得分:1)

我结束了规模和精度,但也在视图中添加了number_to_currency方法。