What is integer.to_f in Ruby?
Overview
The to_f method in Ruby is used to convert the value of an integer number into a float value.
Note: If the integer value does not fit as a float, an infinity value is returned.
Syntax
integer.to_f
Parameter
This method takes the integer value that we want to convert as a parameter value.
Return value
This method returns a float value of the given integer.
Code example
# create some integersint1 = 2int2 = 5int3 = 50int4 = -30**300# convert to float# and print resultsputs int1.to_f # 2.0puts int2.to_f # 5.0puts int3.to_f # 50.0puts int4.to_f # -Infinity
Code explanation
- Lines 2–5: We create some integer values.
- Lines 9–12: We invoke the
to_fmethod on the integer values. And then, we print the results to the console.