How to Convert an Int to String in Golang

To convert an int to a string in Golang, you can use the “strconv.Itoa()”, “strconv.FormatInt()”, or “fmt.Sprintf()” functions.

Method 1: Using Itoa() function

The main way to convert an int to a string is to use the “strconv.Itoa()” function. The “strconv.Itoa()” is a built-in function that returns the string representation of input when integer base 10 value.

Syntax

func Itoa(i int) string

Example

package main

import (
  "fmt"
  "strconv"
)

func main() {
  data := 21
  s := strconv.Itoa(data)
  fmt.Printf("%T, %v\n", s, s)
}

Output

string, 21

The strconv package implements conversions to and from basic data types string representations.

We converted an integer to a string using Itoa() function, which accepts an integer and returns the string.

Method 2: Using FormatInt() function

The FormatInt() is a built-in function of the strconv package that converts an integer value to a string in Golang. The function returns the string representation of i in the given base for 2 <= base <= 36. The result uses the lowercase letters ‘a’ to ‘z’ for digit values >= 10.

Syntax

func FormatInt(i int64, base int) string

Example

package main

import (
 "fmt"
 "strconv"
)

func main() {
 data := int64(-19)

 str10 := strconv.FormatInt(data, 10)
 fmt.Printf("%T, %v\n", str10, str10)

 str16 := strconv.FormatInt(data, 16)
 fmt.Printf("%T, %v\n", str16, str16)
}

Output

string, -19
string, -13

In this example, we defined the int64 version of the integer variable and assigned a -19 value to the data variable.

Then we tried to convert an integer to a string using the FormatInt() function with the base of 10 and 16.

Method 3: Using Sprintf() function

The fmt.Sprintf() is a built-in Golang function that formats based on the specifier. The Sprintf() method accepts the format and string and returns the formatted string.

Syntax

func Sprintf(format string, a ...interface{}) string

Example

package main

import (
 "fmt"
 "io"
 "os"
)

func main() {
 data := 19
 str := fmt.Sprintf("%v \n", data)
 io.WriteString(os.Stdout, str)
}

Output

19

In this example, we format an integer to a string using fmt.Sprintf() function and then use the io.WriteString() function to write the contents of the stated string “str” to the writer “w“, which takes a slice of bytes.

Leave a Comment