Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

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

okwudili onyejiaku

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?
Check if float values are "NaN" in Ruby

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.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring