Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to convert a float to integer in Ruby using the to_i method

okwudili onyejiaku

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_int method 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 values
f1 = 1.2
f2 = 100.224
f3 = 0.3
f4 = 23.333
# convert to integer
# and print results
puts f1.to_i
puts f2.to_i
puts f3.to_i
puts f4.to_i
Convert float values to integers

Explanation

  • Line 2–5: We create float values f1, f2, f3, and f4.
  • Line 8–11: We call the to_i method on the float values we created and print the results to the console.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring