How to convert an int value to string in Go?

golang convert int to string

To convert an int to a string, Golang has a built-in package and methods. To convert an integer to a string, we can use any of the ways. For this type of conversion, we can utilise the strconv and fmt package functions.

We normally receive integer values that we must convert to string type. This integer type must be converted to string type directly.

Convert int to string in Golang

You can use one of the following ways to convert a string to an int:

  • strconv.Atoa: This method convert integer to string.
  • strconv.ParseInt: Thsi method convert Integer value into a string s in the given base (2 to 36) and returns the corresponding value.

Convert Integer value to String Using Itoa

The Itoa() function from the strconv package can be used to convert an integer value to a string in Golang.

Syntax

func Itoa(i int) string

strconv.Itoa() takes an integer as an argument and returns a string.

Let’s see the below example:

package main

import (
  "fmt"
  "strconv"
)

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

Output:

string, 12

Convert int to string Using FormatInt

The FormatInt() function can be used to convert an integer to a string value. This function accepts an integer parameter, converts it into a corresponding string value.

Syntax

func FormatInt(i int64, base int) string

The parameters are :

i: The integer value
base : The base (0,2 to 36)

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

Let’s see the below example:

package main

import (
  "fmt"
  "strconv"
)

func main() {
  i := 12
  a := strconv.FormatInt(int64(i) , 10);        
  fmt.Printf("%T, %v\n", a, a)
  
}

Output:

string, 12

2 Replies to “How to convert an int value to string in Go?”

  1. Thanks for sharing

  2. MiguelViers says:

    informative 🙂

Comments are closed.