Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - conversion string to float return 0.0

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

like image 861
user984621 Avatar asked Feb 28 '13 12:02

user984621


People also ask

How to convert string to float in ruby?

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.

How do you convert a string to an integer in Ruby?

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.


1 Answers

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.

like image 112
froderik Avatar answered Oct 02 '22 20:10

froderik