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.
Author by
user984621
Updated on March 17, 2020Comments
-
user984621 about 4 years
In a variable is stored this value:
$10.00
And I need to get this10.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 about 11 yearsthanks for your answer, but the output is still just
10.0
instead of10.00
. -
froderik about 11 yearsnot for me
1.9.3-p392 :006 > '%.2f' % '$10.00'.delete( "$" ).to_f => "10.00"
-
user984621 about 11 yearsIn totally the same way as you do, the only difference is that the value is stored in database
-
froderik about 11 yearsok - that is weird. You probably have to post a bit more code for me to have an idea. What ruby are you on?
-
user984621 about 11 yearsI am running on
ruby 1.9.3p385
.