如何从rails中的float中删除小数点

时间:2014-12-17 04:30:20

标签: ruby-on-rails methods stripe-payments

我想在将价格发送到表单/条带之前从价格中删除小数点。我可以使用不同的方法来做这件事吗?

在我的product.rb模型中,我有:

def monetize_amount
    self.price.to_s.delete(".").to_f
end

在charge_controller中我有:

def create
  @product = Product.find(params[:id])
    # Amount in cents
  **@amount = @product.monetize_amount**

  customer = Stripe::Customer.create(
   :email => 'example@stripe.com',
   :card  => params[:stripeToken]
  )

  charge = Stripe::Charge.create(
   :customer    => customer.id,
   :amount      => @amount,
   :description => 'Rails Stripe customer',
   :currency    => 'usd'
  )

 rescue Stripe::CardError => e
 flash[:error] = e.message
 redirect_to charges_path
end

1 个答案:

答案 0 :(得分:4)

像argentum47那样说。将其转换为以美分为单位的整数值。

class Product < AR::Base
  def price_in_cents
    (price * 100).to_i
  end
end

然后你可以这样做:

charge = Stripe::Charge.create(
   :customer    => customer.id,
   :amount      => @product.price_in_cents,
   #…