无法在Rails中将货币价值转换为美分

时间:2011-11-15 00:49:30

标签: ruby ruby-on-rails-3

我将货币价值记录为整数,例如price_in_cents或fee_in_cents。因此,$ 1.00将作为100存储在数据库中。

在内部,当我的意思是1.00时,我总是在表单中键入100,但我认为在模型中将1.00的表单输入转换为100很简单,但我遇到了麻烦。

无论我输入什么,我的两个值都为0。这是模型:

before_create :convert_money_to_cents
  attr_accessor :price, :fee

  private

  def convert_money_to_cents
    self.price_in_cents = price.to_i * 100
    self.fee_in_cents = fee.to_i * 100
  end

有关它为什么总是零的任何想法?我尝试将字符串转换为各种东西(浮点数),我仍然会得到零。

2 个答案:

答案 0 :(得分:2)

试试这个:

def convert_money_to_cents
  self.price_in_cents = (self.price.to_d * 100).to_i
  self.fee_in_cents = (self.fee.to_d * 100).to_i
end

答案 1 :(得分:0)

我可能会这样做:

class Numeric
  def to_cents
    (self.to_f * 100).to_i
  end
end