How to get the absolute value of a float in Ruby

Overview

In Ruby, we use the abs method to get the absolute value of a float.

Syntax

float_value.abs
Syntax to get the absolute value of a float

Return value

We call float_value.abs to return the absolute value of float_value.

Example

# create float values
f1 = 23.3435
f2 = -2.8945
f3 = 3/4.7
f4 = -23.3435
# get absolute values
puts f1.abs
puts f2.abs
puts f3.abs
puts f4.abs

Explanation

  • Lines 2–5: We create float values f1, f2, f3, and f4.

  • Lines 8–11: We use the abs method to get the absolute values of the float values. Next, we print it to the console.

Free Resources