How to know if a float value is infinite in Ruby
Overview
An infinite number is a number that has no end and is not measurable. We can have infinite numbers that are positive and negative. These numbers are called positive infinity and negative infinity. We can check if a float value is infinite or not by using the infinite? method.
Syntax
fl_num.infinite?
Parameters
This method takes no parameters. They are only invoked on a float object or value.
Return value
The value returned is 1, -1, or nil. 1 is returned if it is infinity or positive infinity. -1 is returned if it is negative infinity. Otherwise, nil is returned.
Code example
# create float valuesf1 = 2.3435f2 = 1.0/0.0 # infinityf3 = -3.4/0.0 # -infinityf4 = 4.34/1.2# check if infinityputs "#{f1} is : #{f1.infinite?}"puts "#{f1} is : #{f2.infinite?}"puts "#{f1} is : #{f3.infinite?}"puts "#{f1} is : #{f4.infinite?}"
Explanation
- Lines 2 to 5: We create some float variables and initialize them with some values.
- Lines 8 to 11: We use the
infinite?method to determine whether the float values are infinite or not. We then print the results on the console.