Absolute Value of a Number
To find absolute value of a number in Go language, use Abs() function of math package. Abs(x) returns the absolute value of x.
In this tutorial, we will learn the syntax of Abs() function, and how to use this function to find the absolute value of a given number.
Syntax
The syntax of Abs() function is
math.Abs(x)
where x
is a floating point value of type float64.
Please note that we have to import “math” package to use Abs() function.
Return Value
The function returns a floating point value of type float64.
Examples
Absolute Value of Negative Number
In the following program, we take a negative value in x
, and find its absolute value.
example.go
package main
import (
"fmt"
"math"
)
func main() {
var x float64 = -3
result := math.Abs(x)
fmt.Println("Absolute Value :", result)
}
Output
Absolute Value : 3
Absolute Value of Positive Number
Absolute value of a positive number would be the same positive number.
In the following program, we find the absolute value of 3.
example.go
package main
import (
"fmt"
"math"
)
func main() {
var x float64 = 3
result := math.Abs(x)
fmt.Println("Absolute Value :", result)
}
Output
Absolute Value : 3
Conclusion
In this Golang Tutorial, we learned how to find absolute value of a given number in Go language, with example programs.