rubyguides

Kernel#Float

Float(arg, exception: true) -> float

Kernel#Float is the Kernel-provided functional converter that turns an argument into a Ruby Float. You call it as Float(arg), with no receiver, because Kernel is mixed into Object and exposes this method as a module function. The conversion is strict: malformed input raises instead of silently turning into zero, which is the main reason to prefer Float() over String#to_f for user-supplied data.

The method has shipped since Ruby 1.0. The exception: keyword arrived in Ruby 2.6, the same release that gave matching exception: false behavior to Integer, Complex, and Rational.

Signature and arguments

Float(arg, exception: true) -> float
ArgumentTypeNotes
argrequired, single positionalThe value to convert. Passing more than one positional argument raises ArgumentError.
exception:keyword, default trueWhen true (the default), conversion failures raise. When false, the call returns nil for any value that cannot be converted. Added in Ruby 2.6.

There is no base: argument. If you need base-N conversion, reach for Integer with base: or parse the string yourself.

Converting numbers and strings

Numeric inputs and well-formed strings are the happy path.

Float(1)              # => 1.0
Float(-3)             # => -3.0
Float(3.14)           # => 3.14
Float(Rational(1, 4)) # => 0.25
Float(Complex(7, 0))  # => 7.0

String parsing follows the standard float grammar: optional sign, digits, an optional fractional part, and an optional exponent. Leading and trailing ASCII whitespace is stripped. Infinity, -Infinity, inf, and nan (any case) are recognized.

Float("0.0")        # => 0.0
Float("  -2.5  ")   # => -2.5
Float("1e3")        # => 1000.0
Float("-Infinity")  # => -Infinity
Float("nan")        # => NaN

How each input type is handled

Float() chooses a conversion path based on the argument’s class.

  • Integer, Float, Rational, and Complex (with zero imaginary part): direct conversion. Complex with a non-zero imaginary part raises RangeError (or TypeError, depending on the Ruby version).
  • String: strict parse against the float grammar. Empty strings, garbage, "1.2.3", "1e", "1_000", and hex-float literals like "0x1.8p0" all raise ArgumentError.
  • nil: raises TypeError. There is no autoboxing of nil to 0.0.
  • Symbol, true, false: all raise TypeError. Symbol has no to_f, and TrueClass / FalseClass are not converted.
  • Any object responding to to_f (such as Time, Date, DateTime): the method falls through to arg.to_f. Time#to_f returns seconds since the epoch as a Float. Anything else raises TypeError.

The exception: false keyword

Pass exception: false when invalid input is expected and you want a clean nil instead of a raised exception.

Float("oops", exception: false)  # => nil
Float(nil,    exception: false)  # => nil
Float(:x,     exception: false)  # => nil

The typical idiom combines the keyword with a fallback default. You parse the input first; if Float() cannot make sense of the string, the whole expression evaluates to nil and the || operator hands you the safe default you provided. This pattern is the standard way to read numeric configuration that might be missing or malformed without crashing the program.

input = ENV.fetch("TIMEOUT", "1.0")
timeout = Float(input, exception: false) || 1.0

This form is roughly twice as fast as the equivalent Float(input) rescue nil, because the keyword path skips Ruby’s exception machinery and never builds an exception object.

Errors you will hit

The two exception classes to remember are ArgumentError (bad string) and TypeError (wrong type). Catching only ArgumentError will not cover nil or symbol inputs.

Float(nil)   # raises TypeError: can't convert nil into Float
Float(:pi)   # raises TypeError (Symbol has no to_f)
Float(true)  # raises TypeError

Float("")           # raises ArgumentError: invalid value for Float(): ""
Float("1.5abc")     # raises ArgumentError: invalid value for Float(): "1.5abc"
Float("1_000")      # raises ArgumentError: invalid value for Float(): "1_000"
Float(1, 2)         # raises ArgumentError: wrong number of arguments (given 2, expected 1)

The last case is a subtle trap. Integer() accepts a base: keyword, so a muscle-memory typo like Float("1.0", base: 2) raises ArgumentError: unknown keyword: :base. Float has no base conversion at all.

Float() vs String#to_f

Both methods turn strings into floats, but they answer different questions. String#to_f is a lenient parser that returns 0.0 for anything it cannot read. Float() is a strict parser that raises on the same inputs.

InputString#to_fFloat()
"3.14xyz"3.14raises ArgumentError
""0.0raises ArgumentError
" 3.14 "3.143.14
"1_000"1000.0raises ArgumentError
"0x1.8p0"0.75 (platform-dependent)raises ArgumentError
"Infinity"Float::INFINITYFloat::INFINITY
"NaN"0.0raises ArgumentError

The rule of thumb: use Float() (with exception: false if needed) when invalid input is a bug — fail loud, fail early, and let the caller decide what to do about it. Use String#to_f when you want a best-effort number and zero is an acceptable fallback, which is often the right call when you are scanning log lines or scraping messy content off the web.

See also

  • Kernel#Integer — the sibling strict parser for integers, with the same exception: keyword.
  • Kernel#String — the functional String() converter for the same Kernel family.
  • Kernel#to_f — the lenient to_f method, called as a fallback for objects that implement it.