How to Find Absolute Value in Golang

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

input: It is a floating point value of type float64.

Return value

The Abs() function returns a floating point value of type float64.

  1. If you pass negative or positive infinity as an argument, it will return positive infinity.
  2. 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

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

That’s it!