【问题标题】:How to make price 0.00 instead of 0.0?如何使价格为 0.00 而不是 0.0?
【发布时间】:2011-09-08 20:30:47
【问题描述】:

我的用户可以输入和创建价格。我想知道如何做到这一点,所以当用户输入 23.5 他们得到 23.50 而不是 0.0 他们得到 0.00。如何将以下能力添加到 t.decimal 或 my price: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

我的脚手架形式:

然后在你看来把 number_to_currency(@model.attribute):

价格:

【问题讨论】:

  • 似乎是输出问题。使用number_to_currency(price) 显示输出。显示显示价格的代码部分。

标签: ruby-on-rails


【解决方案1】:

没有使用精度和比例,我是这样做的:

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

【讨论】:

  • 你能把价格写成 1.00 吗?我继续获得 1.0。
  • 您是否在 show.html.erb 或其他任何地方使用 number_to_currency 或者当您将 def price 作为浮动时自动执行此操作?
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 我的迁移旧了,还可以添加吗?我把它放进去,做了一个 db:reset,加上价格 23.50 还是得到了 23.5。
    • 只要您愿意重新创建表(从而丢失数据库中当前的数据)就可以了,因为您需要运行 rake db:migrate:reset 重新运行所有迁移.否则,只需创建一个新的迁移来更改价格列的数据类型,例如t.change_column :products, :price, :decimal, { :scale =&gt; 2, :precision =&gt; 10 }。有关change_column 的更多信息,请参阅此link
    • 如果你使用 SQLite3,也可以查看post
    • 是的,我正在使用 SQLite3,更改列迁移的外观如何?我迷失在 Rails 生成迁移 ChangePrice------。
    • thisthis
    猜你喜欢
    • 2020-07-29
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2021-12-24
    • 1970-01-01
    • 2013-10-03
    相关资源
    最近更新 更多