Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to know if a float value is infinite in Ruby

okwudili onyejiaku

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 values
f1 = 2.3435
f2 = 1.0/0.0    # infinity
f3 = -3.4/0.0   # -infinity
f4 = 4.34/1.2

# check if infinity
puts "#{f1} is : #{f1.infinite?}"
puts "#{f1} is : #{f2.infinite?}"
puts "#{f1} is : #{f3.infinite?}"
puts "#{f1} is : #{f4.infinite?}"
Check if the float values are 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.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring