Search code examples
rubycurrency

Ruby: Convert dollar (String) to cents (Integer)


How do I convert a string with a dollar amount such as "5.32" or "100" to an integer amount in cents such as 532 or 10000?

I have a solution below:

dollar_amount_string = "5.32"
dollar_amount_bigdecimal = BigDecimal.new(dollar_amount_string)
cents_amount_bigdecimal = dollar_amount_bigdecimal * BigDecimal.new(100)
cents_amount_int = cents_amount_bigdecimal.to_i

but it seems wonky. I want to be sure because this will be an input to the PayPal API.

I've also tried the money gem, but it wasn't able to take strings as inputs.


Solution

  • You can use String#to_r ("to rational") to avoid round-off error.

    def dollars_to_cents(dollars)
      (100 * dollars.to_r).to_i
    end
    
    dollars_to_cents("12")
      #=> 1200 
    dollars_to_cents("10.25")
      #=> 1025 
    dollars_to_cents("-10.25")
      #=> -1025 
    dollars_to_cents("-0")
      #=> 0