Kernel#to_f
obj.to_f -> float 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
When you call to_f on a string, Ruby parses leading numeric characters and ignores the rest. It does not raise an error for invalid input, which is convenient for quick conversions but means you should validate separately when precision matters. Leading whitespace is stripped automatically before parsing begins.
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
The forgiving behaviour of to_f means invalid strings silently return 0.0. This is both a feature and a potential trap: it keeps your code running, but a missing value and an actual zero become indistinguishable without additional checks. For critical data, consider using Float() instead, which raises ArgumentError on invalid input.
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
The examples below show to_f applied to common data-processing scenarios. Each one demonstrates how the method’s forgiving nature makes it a convenient choice for pipeline-style transformations where a missing value should become zero rather than raising an error. This pattern is especially common in ETL scripts and data import tasks.
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
Configuration files often store numbers as strings. Using to_f lets you convert them to floats in a single pass, which is cleaner than writing conditional parsing logic for each key. This pattern is common when loading settings from YAML, JSON, or environment variables.
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
CSV readers return everything as strings, so converting numeric columns with to_f is a standard pattern. The method handles the conversion in one line per column, keeping the data pipeline readable and the code easy to modify when column names change.
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 }
Defining to_f on your own class lets objects participate in numeric operations as if they were numbers. The conversion logic stays inside the class, so callers only need to call .to_f without knowing the internal formula. This is the same convention used by Ruby’s built-in numeric types.
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.
Converting to float safely
to_f is useful when the code needs to accept a value and keep moving even if the input is not perfectly clean. It gives you a float without raising an error, which makes it easy to use in parsing and lightweight data cleanup. That convenience is also why the surrounding code should decide whether silent fallback to 0.0 is acceptable for the problem at hand.
When the value comes from a user or a file, it is often better to validate first and convert second so the code can distinguish “missing” from “zero”. That keeps the meaning of the number clear and prevents accidental defaults from sneaking into calculations. In other words, to_f is simple, but the calling code should still be deliberate about what a zero result means.
Deciding when a forgiving conversion is enough
The forgiving nature of to_f is a strength when you are normalizing inputs from a loose source, such as a CSV file or a form field. It lets the rest of the code continue without a lot of guard clauses, which can be a good trade when the value is only one part of a larger calculation. Still, the caller should know whether that tolerance is acceptable, because a quiet zero can be helpful in one place and misleading in another.