How to return a simpler approximation of a float value in Ruby

Overview

We can return a simpler approximation of a float value by using the rationalize() method.

Syntax

# default 
float_value.rationalize
# with option
float_value.rationalize(opt)

Parameters

  • float_value: This is the float value whose simple approximation we want to get.

  • opt: This is an optional parameter. When this is passed, the approximation result becomes float_value-opt<= result <= float_value+opt. It means that the results are in between the subtraction of the option from the float value, and the sum of the float value and option.

Return value

This method returns a simple approximation of float_value.

Example

# create float values
f1 = 23.3
f2 = 0.2
f3 = 100.5
f4 = -3.00
# rationalize values
r1 = f1.rationalize
r2 = f2.rationalize
r3 = f3.rationalize(2.00)
r4 = f4.rationalize(0.01)
# print results
print "#{r1}\n"
print "#{r2}\n"
print "#{r3}\n"
print "#{r4}\n"

Explanation

In the above code snippet:

  • Lines 2 to 5: We create float variables and initialize them with values.
  • Lines 8 to 11: We invoke the rationalize() method on the float values.
  • Lines 14 to 17: We print the results which are simple approximations to the console.