Go: Compute absolute values


Go has no built-in library function for computing the absolute value of an integer. It's simple to write your own.

func Abs(x int32) int32 {
        if x < 0 {
                return -x
        return x

Warning: The smallest value of a signed integer type doesn't have a corresponding positive value. For example

  • math.MinInt32 equals -2147483648, while
  • math.MaxInt32 equals 2147483647.

There's no good way to deal with this. In fact, Abs returns a negative value in this case:

fmt.Println(Abs(math.MinInt32)) // Output: -2147483648

The C and Java standard libraries also behave like this.


Use math.Abs to compute the absolute value of a floating-point number:

// Abs returns the absolute value of x.
func Abs(x float64) float64

Note the special cases:

Abs(±Inf) = +Inf
Abs(NaN) = NaN


Be the first to comment!