Ruby: convert dollar (string) to cents (integer)

How to convert a string with an amount in dollars, for example, "5.32"or "100", into a whole amount in cents, such as 532or 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 awkward. I want to be sure, because it will be the entrance to the PayPal API.

I also tried the money stone, but it was not able to take the lines as inputs.

+4
source share
3 answers

You can use String # to_r ("to rational") to avoid rounding errors.

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
+16
source
d, c = dollar_amount_string.split(".")
d.to_i * 100 + c.to_i # => 532
+3
source

, :

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

:

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

All Articles