Ruby - conversion string to float return 0.0

50,686

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.

Share:
50,686
user984621
Author by

user984621

Updated on March 17, 2020

Comments

  • user984621
    user984621 about 4 years

    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

  • user984621
    user984621 about 11 years
    thanks for your answer, but the output is still just 10.0 instead of 10.00.
  • froderik
    froderik about 11 years
    not for me 1.9.3-p392 :006 > '%.2f' % '$10.00'.delete( "$" ).to_f => "10.00"
  • user984621
    user984621 about 11 years
    In totally the same way as you do, the only difference is that the value is stored in database
  • froderik
    froderik about 11 years
    ok - that is weird. You probably have to post a bit more code for me to have an idea. What ruby are you on?
  • user984621
    user984621 about 11 years
    I am running on ruby 1.9.3p385.