How to check if a float value is not a number (NaN) in Ruby

Overview

A float value may be an invalid IEEEThe Institute of Electrical and Electronics Engineers floating-point number. This can be confirmed or denied by invoking the nan? method on that particular float value.

Syntax

float_value.nan?

Parameters

float_value: This is the float value that we check to see whether it is a NaN or not.

Return value

The value returned is a boolean. Therefore, it takes one of the following two values:

  • True: This value is returned if the float_value is actually a NaN.

  • False: This value is returned when the float_value is not a NaN.

Code

# create some float values
f1 = 2.3/0.0 # Infinity
f2 = -1.0
f3 = -9.2333/0.0 # -Infinity
f4 = 0.0/0.0
# check if NaN
puts f1.nan?
puts f2.nan?
puts f3.nan?
puts f4.nan?

Code explanation

  • Lines 2–5: We initialize the variables f1, f2, f3, and f4 with some float values.

  • Lines 8–11: We invoke the nan? method on the variables we created, and print the results through the puts method.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources