Skip to content

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

instance method

Kernel#Float

Float(arg, exception: true) → float or nil

Returns arg converted to a float. Numeric types are converted directly, and with exception to String and nil the rest are converted using arg.to_f. Converting a String with invalid characters will result in a ArgumentError. Converting nil generates a TypeError. Exceptions can be suppressed by passing exception: false.

Example
Float(1)                 #=> 1.0
Float("123.456")         #=> 123.456
Float("123.0_badstring") #=> ArgumentError: invalid value for Float(): "123.0_badstring"
Float(nil)               #=> TypeError: can't convert nil into Float
Float("123.0_badstring", exception: false)  #=> nil
See also #fail #fork #exit! #format also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0