High Tech Sorcery

Determining if a string is a float

by on Mar.19, 2011, under Ruby On Rails

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


Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...