如何始终格式化Rails中两位小数的值

时间:2014-04-19 01:13:04

标签: ruby-on-rails activerecord ruby-on-rails-3.2

我正在使用Rails 3.2.17并存储此类项目的价格(示例迁移):

add_column :item_counts, :per_item_cost, :decimal, :precision => 8, :scale => 2

但是如果它是23.00,那就是23.0。我倾向于创建这样的方法:

  def helpers
    ActionController::Base.helpers
  end

  def per_item_cost_formatted
    helpers.number_to_currency(per_item_cost, precision: 2, format: "%n")
  end

有没有办法可以指定它总是输出格式为23.00?类似的东西:

  def per_item_cost
    helpers.number_to_currency(per_item_cost, precision: 2, format: "%n")
  end

导致无限循环。

thx

1 个答案:

答案 0 :(得分:1)

使用number_with_precision

include ActionView::Helpers::NumberHelper

def per_item_cost
  number_with_precision(read_attribute(:per_item_cost), precision: 2)
end