Kernel#to_f
obj.to_f -> float Returns:
Float · Updated March 13, 2026 · Kernel Methods conversion numbers float parsing
The to_f method converts a value to a floating-point number. It’s defined on many Ruby objects and provides a way to extract numeric values from strings and other objects.
Basic Usage with Numbers
# Integers to floats
42.to_f # => 42.0
-100.to_f # => -100.0
# Float to float (returns self)
3.14159.to_f # => 3.14159
# Rational to float
Rational(1, 2).to_f # => 0.5
Rational(22, 7).to_f # => 3.142857142857143
Converting Strings
# String to float
"3.14".to_f # => 3.14
"123.45".to_f # => 123.45
"-98.6".to_f # => -98.6
# Leading/trailing whitespace is ignored
" 42.5 ".to_f # => 42.5
# Scientific notation
"1.5e3".to_f # => 1500.0
"1e-4".to_f # => 0.0001
Edge Cases
# Invalid strings return 0.0
"hello".to_f # => 0.0
"".to_f # => 0.0
# Numbers embedded in strings
"price50".to_f # => 0.0 (stops at non-numeric)
"50.5degrees".to_f # => 50.5
Practical Examples
Processing User Input
def calculate_total(prices)
prices.map(&:to_f).sum
end
calculate_total(["19.99", "5.50", "3.00"]) # => 28.49
Parsing Configuration
config = {
"discount" => "0.15",
"tax_rate" => "0.08",
"shipping" => "5.99"
}
discount = config["discount"].to_f
tax_rate = config["tax_rate"].to_f
shipping = config["shipping"].to_f
Handling CSV Numeric Data
require 'csv'
data = CSV.read("numbers.csv")
# Assume data is [["3.14"], ["2.71"], ["1.41"]]
floats = data.map { |row| row[0].to_f }
Custom Objects
# Define to_f on your own class
class Temperature
attr_reader :celsius
def initialize(celsius)
@celsius = celsius
end
def to_f
@celsius * 9.0 / 5 + 32
end
end
temp = Temperature.new(100)
temp.to_f # => 212.0
Comparison with Integer#to_f
# Integer.to_f is equivalent
42.to_f # => 42.0
Integer(42).to_f # => 42.0
Float(42) # => 42.0
The to_f method is the standard way to convert values to floats in Ruby, widely used in numeric processing and data parsing.