In this section, we will learn how to convert a string value into float value.
How to Convert a String value to Float in Ruby?
When you have a string value in your program that has a float value and you want to convert that string into the float type, we can use the to_f method.
Note that this method works only if the target string value starts with numbers! But it doesn’t matter if it also contains other types of characters as long as its beginning characters are float numbers.
This method also works with integer values as well and basically will add the decimal part (.0) to the value and return a float number as a result.
Also remember that if you have a user made object, you can override this method in that object and set a float value to be returned whenever you’ve called the method.
Note: you don’t really need to call the to_f method on an integer value where the target operation requires a floating type of value! Ruby will automatically run the necessary operations to convert your integer value into float if needs to be.
Ruby to_f Method Syntax:
The method does not take an argument. Simply call this method on an integer or a string value and you’ll get the floating representation of that value.
Example: using to_f method in Ruby
puts 333.to_f puts "324.23fst".to_f
Output:
333.0 324.23