0
0
RubyHow-ToBeginner · 2 min read

Ruby How to Convert String to Float with Examples

In Ruby, you can convert a string to a float by using the to_f method, like "3.14".to_f which returns 3.14.
📋

Examples

Input"3.14"
Output3.14
Input"0.001"
Output0.001
Input"abc"
Output0.0
🧠

How to Think About It

To convert a string to a float in Ruby, think of it as asking Ruby to read the string and turn it into a decimal number. The to_f method looks at the string from left to right and converts any valid number it finds at the start. If the string doesn't start with a number, it returns 0.0.
📐

Algorithm

1
Take the input string.
2
Use the <code>to_f</code> method to convert the string to a float.
3
Return the resulting float value.
💻

Code

ruby
str = "3.14"
float_value = str.to_f
puts float_value
Output
3.14
🔍

Dry Run

Let's trace converting the string "3.14" to a float.

1

Input string

str = "3.14"

2

Convert using to_f

float_value = str.to_f # float_value becomes 3.14

3

Print result

puts float_value # outputs 3.14

StepVariableValue
1str"3.14"
2float_value3.14
3output3.14
💡

Why This Works

Step 1: Using to_f method

The to_f method reads the string and converts the initial part that looks like a number into a float.

Step 2: Handling invalid strings

If the string does not start with a number, to_f returns 0.0 instead of raising an error.

🔄

Alternative Approaches

Using Float() method
ruby
str = "3.14"
float_value = Float(str)
puts float_value
Float() raises an error if the string is not a valid float, so it is stricter than to_f.
Using Kernel#Float with rescue
ruby
str = "abc"
float_value = begin
  Float(str)
rescue ArgumentError
  0.0
end
puts float_value
This method safely converts or returns 0.0 if conversion fails, combining strict parsing with error handling.

Complexity: O(n) time, O(1) space

Time Complexity

The to_f method scans the string once from left to right, so it takes linear time relative to the string length.

Space Complexity

Conversion uses constant extra space since it only stores the resulting float.

Which Approach is Fastest?

to_f is fastest and simplest for basic conversion. Float() is slightly slower due to error checking but safer.

ApproachTimeSpaceBest For
to_fO(n)O(1)Quick conversion, no error on invalid input
Float()O(n)O(1)Strict conversion, raises error on invalid input
Kernel#Float with rescueO(n)O(1)Safe conversion with error handling
💡
Use to_f for simple conversion, but use Float() if you want to catch invalid strings as errors.
⚠️
Expecting to_f to raise an error on invalid strings, but it returns 0.0 silently instead.