Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
float
rational
communitycreator

How to get the rational of a float value in Ruby

okwudili onyejiaku

Overview

We can get the rational of a float value, the numerator, and the denominator by using the to_r method.

Syntax

float_value.to_r

Return value

This method returns the rational of float value float_value.

Example

# create float values
f1 = 2.5
f2 = -8.00
f3 = 0.5555
f4 = 10.13425

# get the rationals
# and print results
print "#{f1.to_r} \n"
print "#{f2.to_r} \n"
print "#{f3.to_r} \n"
print "#{f4.to_r}"
Getting the rationals of float values in Ruby

Explanation

In the above code snippet:

  • Lines 2 to 5: We create four float values: f1, f2, f3, and f4.
  • Line 9 to 12: We invoke the to_r method on the float values and rationals are returned. Then we print the results to the console.

RELATED TAGS

ruby
float
rational
communitycreator
RELATED COURSES

View all Courses

Keep Exploring