I’m trying to initialize a variable as a float and then add to it in a times loop. Here’s my code:
amt = 0.0
5.times do
amt = amt + ("%.2f" % (item.price * 0.05))
end
Here’s the error:
String can't be coerced into Float
EDIT:
I’ve changed the 1.times do. I had adapted my code so that it would be more readable, the 1.times wasn’t in my actual code.
Firstly, try not to use floats for money – what you’ll need to do in this case is use BigDecimal – floating point math is not accurate.
To use BigDecimal, require ‘bigdecimal’ in your application.rb
Then, what you want is: