How to convert int to string in Golang

  • 14 August 2020
  • ADM

 

How to convert int to string in Golang - images/logos/golang.jpg

 

If you need help how to install Golang check the references links.

Int to string

To convert int to string in Golang you can use one of the following methods:

  • strconv.FormatInt: FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
  • strconv.Itoa: Itoa is shorthand for FormatInt(int64(i), 10)
package main

import (
	"fmt"
	"strconv"
)

func main() {

	i1 := 1234

	/** converting the i1 variable into a string using Itoa method */
	str1 := strconv.Itoa(i1)
	fmt.Println(str1)

	i2 := 5678
	/** converting the i2 variable into a string using FormatInt method */
	str2 := strconv.FormatInt(int64(i2), 10)
	fmt.Println(str2)
}

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build int_to_string.go

Then depending if you are on Linux or windows the binary file is created.

To run the application execute the command.

Linux

$ int_to_string

Windows

c:\Users\adm\go\tutorials> int_to_string.exe

If you want to compile and run the application in one single step run the following command:

go run int_to_string.go

Output

will display the int numbers in string format.

1234
5678

 

References