How to check if a float value in Ruby is less than 0

Overview

In Ruby, we can check if the float value is less than zero (0) using the negative? method.

Syntax

float_value.negative?

Parameters

float_value: This is the value that we want to check.

Return value

It returns true if the float_value is less than 0. Otherwise, it returns false.

Code example

# create some float values
f1 = 2.3/0.0 # Infinity
f2 = -1.0
f3 = -9.2333/0.0 # -Infinity
f4 = 0.0/0.0
f5 = 221.2222
# check if less than 0
puts f1.negative?
puts f2.negative?
puts f3.negative?
puts f4.negative?
puts f5.negative?

Explanation

  • Lines 2-6: We initialize the float variables f1, f2, f3, f4, f5, and f6.
  • Lines 9-13: We invoke the negative? method on the float variables we’ve created and print the results on the console.

Free Resources