How to convert a float to integer in Ruby using the to_i method
Overview
The to_i method returns a float that is truncated to an integer. This means that it converts a float value to an integer.
Note: The
to_intmethod can also achieve this.
Syntax
float_value.to_i
Parameters
float_value: This is the float value that invokes the method. It is this float value we want to convert to an integer.
Return value
The to_i method returns an integer.
Example
# create float valuesf1 = 1.2f2 = 100.224f3 = 0.3f4 = 23.333# convert to integer# and print resultsputs f1.to_iputs f2.to_iputs f3.to_iputs f4.to_i
Explanation
- Line 2–5: We create float values
f1,f2,f3, andf4. - Line 8–11: We call the
to_imethod on the float values we created and print the results to the console.