【问题标题】:How can I allow Stripe to accept whole and decimal values on rails?如何允许 Stripe 在导轨上接受整数和十进制值?
【发布时间】:2018-02-14 21:04:01
【问题描述】:

在一个 rails 项目上实现了 Stripe。 Stripe 默认接收 '500' 并发送 5.00 到他们的 API。如果我做 amount.to_i*100 我可以得到 '500' 保持 500,但是当 amount = 5.67 时仍然得到 5.00。

如何更改控制器、视图或字段以正确允许两者?

控制器代码

@amount = params[:amount].to_i*100

查看代码

<input class="form-field two-decimals" name="amount" type="number" step="any" >

【问题讨论】:

  • to_i 用于 integer 转换,截断小数点后的任何内容。考虑使用to_f,它将从字符串中读取一个浮点数。
  • 尝试使用(params[:amount].to_f*100).round 从浮点字符串中获取整数值。请注意,我没有使用.to_i,因为这可能会导致数学错误,而是选择使用.round

标签: ruby-on-rails decimal stripe-payments currency


【解决方案1】:

你可以这样做:

@amount = sprintf("%.2f",(params[:amount])).delete '.'

【讨论】:

  • 这就是我最终采用的方法。 @a = params[:amount].to_f*100 @amount = @a.to_i
【解决方案2】:

Stripe 只接受整数,要获得正确的整数,您可以将数量乘以 100。

(@amount * 100).to_i => 44.53 * 100 = 4453.0.to_i 并转换为整数4453

def charge
    begin
        charged = Stripe::Charge.create(
          :amount   => (@amount * 100).to_i,
          :currency => "usd",
          :customer => @customer_id
        )
    rescue Stripe::InvalidRequestError, Stripe::AuthenticationError, Stripe::APIConnectionError, Stripe::StripeError => e
        puts e.message
        return false
    end
    charged
end

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多