Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
string
float
conversion
communitycreator

How to convert leading characters of a string to a float in Ruby

okwudili onyejiaku

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 strings
str1 = "234hello"
str2 = "15.4kg"
str3 = "welcome"

# comvert to floatin
# point number
puts str1.to_f;
puts str2.to_f;
puts str3.to_f;
Converting Leading Characters of a String to Float in Ruby

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.

RELATED TAGS

ruby
string
float
conversion
communitycreator
RELATED COURSES

View all Courses

Keep Exploring