In a variable is stored this value: $10.00
And I need to get this 10.00
I've tried to convert this value to float:
new_price = '%.2f' % (price.to_f)
but I get just 0.0
.
What's wrong with that? I've tried also
price = price.strip
price[0]=""
new_price = '%.2f' % (price.to_f)
But even this didn't help me... where is a problem?
Thanks
Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.
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.
You need to remove the $
first. The whole thing like this:
'%.2f' % '$10.00'.delete( "$" ).to_f
or
'%.2f' % '$10.00'[1..-1].to_f
if you like density and may encounter non dollars.
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