Using to_f has the problem of returning 0.0 for invalid strings. So for a project I needed to know if a string was a valid float or not and came across this helpful page: ruby on rails – Determine if a string is a valid float value – Stack Overflow. My favorite option was this:
class String
def valid_float?
# The double negation turns this into an actual boolean true - if you're
# okay with "truthy" values (like 0.0), you can remove it.
!!Float(self) rescue false
end
end