【问题标题】:How to always format a value coming out as two decimal spaces in Rails如何始终在 Rails 中格式化输出为小数点后两位的值
【发布时间】:2014-04-19 01:13:04
【问题描述】:

我正在使用 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

导致无限循环。

【问题讨论】:

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


    【解决方案1】:

    使用number_with_precision:

    include ActionView::Helpers::NumberHelper
    
    def per_item_cost
      number_with_precision(read_attribute(:per_item_cost), precision: 2)
    end
    

    【讨论】:

    • 谢谢你;嗯.....所以做了一些可以给我 500 的 SystemStackError (stack level too deep): actionpack (3.2.17) lib/action_dispatch/middleware/reloader.rb:70 的事情,这就是为什么我用 _formatted 来命名它的原因。
    • 不错 - thx vee; read_attribute 做到了;必须等待几分钟
    • @timone,太好了!这是read_attribute 上的文档
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多