How to check if a float value is not a number (NaN) in Ruby
Overview
A float value may be an invalid 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 thefloat_valueis actually aNaN. -
False: This value is returned when thefloat_valueis not aNaN.
Code
# create some float valuesf1 = 2.3/0.0 # Infinityf2 = -1.0f3 = -9.2333/0.0 # -Infinityf4 = 0.0/0.0# check if NaNputs f1.nan?puts f2.nan?puts f3.nan?puts f4.nan?
Code explanation
-
Lines 2–5: We initialize the variables
f1,f2,f3, andf4with some float values. -
Lines 8–11: We invoke the
nan?method on the variables we created, and print the results through theputsmethod.