How to know if a float value is finite in Ruby

Overview

A float value is finite if it has an end or it is measurable. It is not finite if it is infinity, negative infinity (-infinity) or Not a Number (NaN). To determine whether a float value is finite or not, we use the finite? attribute.

Syntax

flt.finite?

Return value

The value returned is a Boolean value. true is returned if the float value is finite. If it isn’t, false is returned.

Code example

# create float values
f1 = 4.8
f2 = 3.0/ 0.0 # infinity
f3 = -2.33/0.0 # -infinity
f4 = 499.11111
# check if finite
puts f1.finite?
puts f2.finite?
puts f3.finite?
puts f4.finite?

Explanation

  • Lines 2-5: We create some float values.
  • Lines 8-11: We use finite? to check if the values are finite, and print the results to the console.

Free Resources