Ruby on rails 使用Mongoid的货币的数据类型

Ruby on rails 使用Mongoid的货币的数据类型,ruby-on-rails,ruby,ruby-on-rails-3,mongodb,mongoid,Ruby On Rails,Ruby,Ruby On Rails 3,Mongodb,Mongoid,我想浮动汇率对货币来说并不理想。Mongoid支持Float和BigInteger。存储和使用货币值的最佳方法是什么?如果您没有实际使用分数部分,也就是说,如果您只存储了预定标度的整数值,则浮动可以用于货币。浮点存储整数并精确执行整数运算 当然,在这一点上,您也可以使用整数。您可能想看看 它的工作方式是以美分表示货币金额,并使用整数。 您可以按照这种方式将数据存储为整数,这样就不需要处理浮点精度 西蒙尼说的 我刚刚在我的项目中插入了money gem,您也可以将其存储为money类型 class

我想浮动汇率对货币来说并不理想。Mongoid支持Float和BigInteger。存储和使用货币值的最佳方法是什么?

如果您没有实际使用分数部分,也就是说,如果您只存储了预定标度的整数值,则浮动可以用于货币。浮点存储整数并精确执行整数运算


当然,在这一点上,您也可以使用整数。

您可能想看看

它的工作方式是以美分表示货币金额,并使用整数。 您可以按照这种方式将数据存储为整数,这样就不需要处理浮点精度

西蒙尼说的

我刚刚在我的项目中插入了money gem,您也可以将其存储为money类型

class Product
  include Mongoid::Document

  field :price,    type: Money
end

Money.class_eval do

  # Converts an object of this instance into a database friendly value.
  def mongoize
    [cents, currency.to_s]
  end

  class << self

    # Get the object as it was stored in the database, and instantiate
    # this custom class from it.
    def demongoize(object)
      cur = object[1] || Money.default_currency
      Money.new(object[0], cur)
    end

    # Takes any possible object and converts it to how it would be
    # stored in the database.
    def mongoize(object)
      case object
      when Money
        object.mongoize
      else object
      end
    end

    # Converts the object that was supplied to a criteria and converts it
    # into a database friendly form.
    def evolve(object)
      case object
      when Money then object.mongoize
      else object
      end
    end
  end

end   
类产品
include Mongoid::Document
字段:价格,类型:货币
结束
金钱、阶级、价值
#将此实例的对象转换为数据库友好值。
蒙哥伊兹酒店
[美分,货币。对美元]
结束
课堂上我读到,当使用货币时,需要“固定精度”的数字库。这是一个示例讨论。