Golang Absolute Value
What is the Absolute Value of a Number?
The absolute value of a number is the distance between the number and zero on a number line. For example, the absolute value of -5 is 5, and that of 5 is 5.
How to Get the Absolute Value of a Number in Golang
To find the absolute value of a number in Golang, use the math.Abs()
function. This function takes a float64
as input and returns a float64
as output.
You have to import the math
package to use this function. You can do this by adding the following line to the top of your file:
Absolute Value of a Number in Golang Example
Let’s look at an example of how to get the absolute value of a number in Golang.
math.Abs()
Special Cases
If the number is NaN
, math.Abs()
will return NaN
.
If the number is +Inf
, math.Abs()
will return +Inf
.
Absolute Value for int64 in Golang
If you want to get the absolute value of an int64
, you can convert it to a float64
and then use the math.Abs()
function.
You can also use the math.Abs()
function on an int
or int32
by converting it to a float64
.
Application of Absolute Value in Golang
The absolute value of a number is useful for finding the distance between two points on a number line. For example, if you have two points on a number line, you can find the distance between them by subtracting the smaller point from the larger point and then taking the absolute value of the result.