Get Price in Cents for Stripe


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?


There is actually a very easy way to do this, directly from a decimal without converting to a float first. Given:

decimal price = BigDecimal('100.00')

You can use BigDecimal's fix() and frac() methods to take the first part, multiply by 100 and add the fraction:

price_in_cents = ((decimal_price.fix * 100) + decimal_price.frac).to_i

Another seemingly simple possibility is to use string manipulation. You can convert the decimal to a string, strip the period, and convert to integer like:

price_in_cents = decimal_price.to_s.sub('.', '').to_i

But the gotcha here is that decimal_price.to_s == '100.0' not '100.00'. If there are non-zero digits in the fraction, then they would be preserved in the conversion, but otherwise one is lost. So if decimal_price == 111.11 then the above string manipulation would return the expected result.

By : Christian

This video can help you solving your question :)
By: admin