instance method
Kernel#Float
(::_ToF float_like, ?exception: true) -> ::Float
(::_ToF float_like, exception: bool) -> ::Float?
(untyped, ?exception: bool) -> ::Float?
Float(arg, exception: true) → float or nil
kernel.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.0.0/kernel.rb, line 194
def Float(arg, exception: true)
if Primitive.mandatory_only?
Primitive.rb_f_float1(arg)
else
Primitive.rb_f_float(arg, exception)
end
end
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 an 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