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

abtree

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.

Cary Swoveland

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Ruby Converting dollar integer into String

From Dev

Convert a whole number amount of cents to a readable dollar amount in JavaScript?

From Dev

How can I convert a value in cents to a dollar value

From Dev

What is the best method to obtain dollar value with cents from a string?

From Dev

Ruby On rails: Cannot convert String to Integer

From Dev

Ruby - 'read': can't convert String into Integer

From Dev

Ruby : TypeError: can't convert String into Integer

From Dev

What is the best way to convert Dollars (Big Decimal) in Cents (Integer) in java?

From Dev

Ruby Hash: can't convert String into Integer TypeError

From Dev

`[]': Can't convert String into Integer (TypeError) Ruby script

From Dev

Convert Cents to Euro

From Java

Java - Convert integer to string

From Java

Convert integer to string Jinja

From Dev

How to convert an integer to a string

From Dev

Convert integer list to a string

From Dev

Swift: convert string into integer

From Dev

Convert List<Integer> to String

From Dev

Javascript convert string to integer

From Dev

Convert String to Integer JSP

From Dev

Convert String (with comma) into integer

From Dev

convert string value in to integer

From Dev

Convert String (timestamp) to integer

From Dev

Trying to convert String to Integer

From Dev

How to convert a string to an integer

From Dev

Convert String (with comma) into integer

From Dev

Convert List<Integer> to String

From Dev

How can I turn a string containing a dollar amount into an integer?

From Dev

Multiplying string by integer vs integer by string in ruby

From Dev

Superscript cents in an attributed string