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 valuesf1 = 23.3435f2 = -2.8945f3 = 3/4.7f4 = -23.3435# get absolute valuesputs f1.absputs f2.absputs f3.absputs f4.abs
Explanation
-
Lines 2–5: We create float values
f1,f2,f3, andf4. -
Lines 8–11: We use the
absmethod to get the absolute values of the float values. Next, we print it to the console.