Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

String#to_f

() -> ::Float
to_f → float
Returns the result of interpreting leading characters in +self+ as a Float:

  '3.14159'.to_f  # => 3.14159
  '1.234e-2'.to_f # => 0.01234

Characters past a leading valid number are ignored:

  '3.14 (pi to two places)'.to_f # => 3.14

Returns zero if there is no leading valid number:

  'abcdef'.to_f # => 0.0

See Converting to Non-String.

See also #to_c #to_i #swapcase! #to_r also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0