To find an absolute value in Golang, you can use the “math.Abs()” function. The math.Abs() is a built-in function “used to find the absolute value of any given number”.
Syntax
math.Abs(input)
Parameters
An input is a floating point value of type float64.
Return value
The Abs() function returns a floating point value of type float64.
- If you pass negative or positive infinity as an argument, it will return positive infinity.
- If you pass a non-numeric argument like a string, the Abs() function returns NAN.
Example 1: Absolute value of the positive number
package main
import (
"fmt"
"math"
)
func main() {
var data float64 = -19
result := math.Abs(data)
fmt.Println("Absolute Value is:", result)
}
Output
Absolute Value : 19
In this example, we defined float variable data whose value is -19, which is negative.
Using the Abs() method, we calculated the absolute value of the negative value -19, which is positive 19.
Example 2: Absolute value of the positive number
To calculate the absolute value of a positive number in Golang, you can use math.Abs() function.
package main
import (
"fmt"
"math"
)
func main() {
var data float64 = 21
result := math.Abs(data)
fmt.Println("Absolute Value of positive number is:", result)
}
Output
Absolute Value of positive number is: 21
Example 3: Absolute value between two points
You can use the math.Abs() function to find the distance between two points in Golang.
package main
import (
"fmt"
"math"
)
func main() {
x1 := 10.0
x2 := 8.0
y1 := 6.0
y2 := 4.0
distance := math.Sqrt(math.Pow(math.Abs(x1-x2), 2) + math.Pow(math.Abs(y1-y2), 2))
fmt.Println(distance)
}
Output
2.8284271247461903
The math.Abs() function returns an error; if you directly pass an integer value to it, the value gets automatically typecasted into a float64, and the function works as intended, as displayed.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.