16

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

3 Answers 3

22

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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

To set it in a variable:

 current_price= '%.2f' % '$10.00'.delete( "$" ).to_f

The more common error, is a value in the thousands where there's a comma in the string like: 10,000.00. The comma will cause the same truncation error, but the decimal won't, and many programmers won't even catch it (we don't even notice the comma anymore). To fix that:

current_price= '%.2f' % '10,000.00'.delete( "," ).to_f

Comments

-1

Adding on to froderick's answer of:

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. you need to format the code for output to ensure that you get two decimal places >with

You need to format your output string to ensure you get two decimal places.

puts "Current amount: #{format("%.2f", amount)}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.