user984621
user984621

Reputation: 48443

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

Upvotes: 16

Views: 52554

Answers (3)

user5099519
user5099519

Reputation:

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

Upvotes: 0

Jexoteric
Jexoteric

Reputation: 127

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)}"

Upvotes: -1

froderik
froderik

Reputation: 4808

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.

Upvotes: 22

Related Questions