Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#to_f

str.to_f → float

Returns the result of interpreting leading characters in str as a floating point number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0.0 is returned. This method never raises an exception.

Example
"123.45e1".to_f        #=> 1234.5
"45.67 degrees".to_f   #=> 45.67
"thx1138".to_f         #=> 0.0
See also #toeuc #to_i #to_d #tojis also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1