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.
One dollar equals 100 cents. Dollars are in paper notes called bills and come in $100, $50, $20, $10, $5 and $1. Cents come in coins. If you'd like to sound like a true American, these coins are called a quarter (25 cents), a dime (10 cents), a nickel (5 cents) and a penny (1 cent).
What is the best way to convert Dollar which is a double value to cents which is an int value in Java. Currently I use the following approach: Double cents = new Double(dollar*100); int amount = cents.
To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0. Here is an example, that converts the string "100" to Integer or decimal number: str = "100" num = str.to_i puts num
The source code to convert an integer number into the string is given below. The given program is compiled and executed successfully. In the above program, we created a variable num initialized with 10. Then we converted the integer number into the string using the to_s () function and printed the result.
You’re probably familiar with this first group of conversion methods. These methods return a new object of a specific class that represents the current object. “I want to convert the Range 1..10 into an Array that represents that range.” There are ways in which Ruby calls these conversion methods for you implicitly.
If you pass the Integer method a value that can’t be converted, Ruby will raise an error: You can then handle the error and provide a message to the user, asking them to provide better data. This approach is less convenient, but it can result in better data integrity, since your data won’t be coerced.
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
d, c = dollar_amount_string.split(".")
d.to_i * 100 + c.to_i # => 532
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With