How to convert leading characters of a string to a float in Ruby
Overview
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.
Syntax
str.to_f
Parameters
str: This is the string whose leading number characters we want to convert to a floating point number.
Return value
The value returned is a floating point number of the leading number characters present in a string.
Code example
# create stringsstr1 = "234hello"str2 = "15.4kg"str3 = "welcome"# comvert to floatin# point numberputs str1.to_f;puts str2.to_f;puts str3.to_f;
Explanation
-
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.