【发布时间】:2010-11-04 21:04:51
【问题描述】:
我猜浮动对于货币来说并不理想。 Mongoid 支持 Float 和 BigInteger。存储和使用货币价值的最佳方法是什么?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid
我猜浮动对于货币来说并不理想。 Mongoid 支持 Float 和 BigInteger。存储和使用货币价值的最佳方法是什么?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 mongodb mongoid
您可能想看看Money gem。
它的工作方式是以美分表示货币金额并使用整数。 您可以按照这种方式将数据存储为整数,这样您就不需要处理浮点精度。
【讨论】:
西蒙娜怎么说。
我刚刚在我的项目中插入了 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
【讨论】:
如果您实际上不使用小数部分,即仅存储预缩放的整数值,则浮点数对于货币来说可以正常工作。浮点数存储整数并精确执行整数运算。
当然,到那时,你也可以使用整数。
【讨论】: