abtree
abtree

Reputation: 335

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.

Upvotes: 7

Views: 5561

Answers (3)

Blair Anderson
Blair Anderson

Reputation: 20171

I started with the original accepted answer, but had to make some important fixes along the way:

def dollars_to_cents(string=nil)
  # remove all the signs and formatting
  nums = string.to_s.strip.delete("$ CAD ,")
  # add CENTS if they do not exit
  nums = nums + ".00" unless nums.include?(".")
  return (100 * nums.strip.to_r).to_i
end

So far works with these inputs:

  • CAD 1,215.92
  • CAD 1230.00
  • $11123.23
  • $123
  • 43234.87
  • 43,234.87

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110675

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

Upvotes: 30

sawa
sawa

Reputation: 168091

d, c = dollar_amount_string.split(".")
d.to_i * 100 + c.to_i # => 532

Upvotes: 3

Related Questions