Search code examples
rubybigdecimal

Convert BigDecimal to cents


I want to convert a BigDecimal in Ruby to cents, here is what I did:

amount = BigDecimal('19.95')
#=> #<BigDecimal:7f80bc726b38,'0.1995E2',18(18)> 
amount_in_cents = amount*100
#=> #<BigDecimal:7f80bc794cc8,'0.1995E4',9(45)> 
amount_in_cents.to_f
#=> 1995.0
amount_in_cents.ceil
#=> 1995

So ceil gives me the right amount in cents, the amount I need to communicate to the payment provider. At the moment I'm not 100% sure if what I did here is correct. Maybe somebody knows a better way?


Solution

  • You can also use to_i, which would communicate your intent even better, unless you expect to be dealing with fractional cents (in which case, to_i seems to truncate towards zero).