How can we check if a float value is positive in Ruby?

Overview

Numbers greater than 0 are positive numbers. We can check if a number is greater than 0 by using the positive? method. This method returns either true or false.

Syntax

float_value.positive?

Parameters

float_value: This is the float value that we want to check to see if it is greater than 0.

Return value

The result of this method is always a boolean value. If the float_value is greater than 0, then true is returned. However, if the float_value is not greater than 0, then false is returned.

Code example

# create some values
f1 = 3.444
f2 = 0.0
f3 = 0.3
f4 = 100 / 0.0
# check if greater than 0
# and print results
puts f1.positive? # true
puts f2.positive? # false
puts f3.positive? # true
puts f4.positive? # true

Code explanation

  • Lines 2–5: We create the float values f1, f2, f3, and f4.
  • Lines 9–12: We invoke the positive? method on the float values we created, and we print the returned values to the console.

Free Resources