To convert a string to a float in Ruby, you can use the 'to_f' method.
In this example,
str1
with a value of "3.14"
.to_f
method to convert the string to a float and store the result in a variable float1
.float1
.# Convert "3.14" String to Float
str1 = "3.14"
float1 = str1.to_f
puts "Float value is: #{float1}"
Float value is: 3.14
In this example,
str2
with a value of "10.5"
.to_f
method to convert the string to a float and store the result in a variable float2
.float2
.# Convert "10.5" String to Float
str2 = "10.5"
float2 = str2.to_f
puts "Float value is: #{float2}"
Float value is: 10.5
In this tutorial, we learned How to convert String to Float in Ruby language with well detailed examples.