Skip to content
Home » How to print the absolute value for an integer number in Golang

How to print the absolute value for an integer number in Golang

Learn about How to print the absolute value for an integer number in Golang in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

How to print the absolute value for an integer number in Golang

// Golang program to print the absolute value for an integer number

package main
import "fmt"

func GetIntAbs(val int64) int64 {
	if val < 0 {
		return -val
	}
	return val
}

func main() {
    var val int64 = -43
   
    fmt.Printf("Absolute value of %d is %d",val,GetIntAbs(val)) 
}

In the above program, we declare the package main. The main package instructs the Go language compiler that the package must be compiled and an executable file generated. We imported the fmt package, which contains the files of the fmt package, and then we can use a function related to the fmt package. As we know that, there is no predefined function to get the absolute value for an integer number then we created a user define function to get the absolute value of an integer number. Here, we created a variable value, which is initialized with -43. After that, we get the absolute value using user define function GetIntAbs() and print the result on the console screen.

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Codes :
How to print the absolute value of float number in Golang
How to demonstrate the use of Printf() and Scanf() function in Golang