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.
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources