The to_f
string method converts leading characters in a string to a floating point number. If there is no number character at the leading position in the string, a 0.0
result is returned.
str.to_f
str
: This is the string whose leading number characters we want to convert to a floating point number.
The value returned is a floating point number of the leading number characters present in a string.
# create stringsstr1 = "234hello"str2 = "15.4kg"str3 = "welcome"# comvert to floatin# point numberputs str1.to_f;puts str2.to_f;puts str3.to_f;
Line 2 to 4: We create some strings.
Line 8 to 10: We convert the leading number strings to a floating point number. Then, we print them.