【问题标题】:Convert string into Currency format将字符串转换为货币格式
【发布时间】:2012-01-04 20:59:06
【问题描述】:

使用 Ruby 和 Haml,我有一个属性,即成本。我相信(我是 ruby​​ 新手)它将是一个浮点数

目前,下面的行以 4.5 而不是 4.50 的格式输出我的小数,这正是我想要的。

%span.value= "£#{event.beers.first.cost)}"

这是我的啤酒类文件。

class Beer
  include Mongoid::Document
  embeds_many :ratings

  field :name, type: String
  field :country, type: Country
  field :cost, type: Float
  field :photos, type: PhotoArray, default: PhotoArray.new
end

【问题讨论】:

    标签: ruby mongodb mongoid haml


    【解决方案1】:

    如果你使用 Rails,你可以使用number_to_currency helper

    【讨论】:

      【解决方案2】:

      如果您说的是美国货币,包括:

      • 小数点后每三位逗号
      • 小数点右边最多两位数
      • 如果美分为零,则不显示小数点

      试试这个

      vals = [123.01, 1234.006, 12, 1234567, 12345678.1,1.001]
      vals.map{|num| 
                  num.sprintf('%.2f',num)
                     .gsub('.00','')
                     .reverse
                     .scan(/(\d*\.\d{1,3}|\d{1,3})/)
                     .join(',')
                     .reverse
              }
      

      在调试器中生成以下内容:

      => ["123.01", "1,234.01", "12", "1,234,567", "12,345,678.10", "1"]

      可以通过编辑连接字符串对其进行调整,使其对某些欧洲格式有用,但我对欧洲惯例了解不多。

      【讨论】:

        【解决方案3】:

        查看字符串格式化方法,Kernel::sprintf 文档有它的所有参数。

        在这种情况下,您可能希望通过 %span.value= "%%pound;%.2f" % event.beers.first.cost 获得 4.50 而不是 4.5。

        【讨论】:

        • 谢谢,我最终使用的代码行是 "£#{"%.2f" % event.beers.first.cost}"
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-30
        • 2013-12-22
        • 1970-01-01
        • 1970-01-01
        • 2015-12-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多