Get Price in Cents for Stripe

ruby, ruby-on-rails, stripe-payments

Solution

Ruby has several methods available to floats, depending on what you need:

- `(cart.total_price * 100).to_i (discards all decimals)`

- `(cart.total_price * 100).round # .round(numofdecimals)`

- `(cart.total_price * 100).floor # 1.3 => 1`

- `(cart.total_price * 100).ceil # 1.3 => 2`

- `(cart.total_price * 100).to_r #to rationals, e.g. 2.5 => 5/2`

I hope this helps.

Problem

I have to send the amount of some price in cents to Stripe in order to make charge against a card. In my app, the `total_price` value is a decimal, i.e in dollars and cents. Obviously, I can convert this to cents by multiplying by 100: ``` total_price * 100 ``` But the result is still a decimal, and Stripe gives me an 'Invalid amount' error. I know there can be issues with rounding floats. I want to know the safest way to cast my `total_price` to an integer in Rails. I have seen some reference to a money gem but is this necessary in this case?

Original source