Converting Integer to String in Golang

Integers and strings are converted to each other on many different occasions. This post will provide the ways we can convert an integer to a string in Go.

The naive typecasting

We may try doing a simple type conversion using the string() function to convert an integer to a string. It will work and produce a character. That’s not what we want when we convert an integer to a string.

package main

import (
	"fmt"
)

func main() {
	a := 1234
	
	// we want "1234"
	fmt.Println(string(a))     // Ӓ
}

The naive type conversion fails to produce the result as it produces a rune.

Using the strconv package

The strconv package does this optimally. It has methods that produce the output we require when we convert an integer to a string.

The Itoa method

The Itoa method takes an integer and produces the string version of that integer. Here is an example.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	a := 1234
	fmt.Println(strconv.Itoa(a))     // 1234
}

This method works as expected and produces the correct output.

The FormatInt method

The FormatInt method is another method that is available via the strconv package. It formats the integer to a string representation. The function signature is as follows:

func FormatInt(i int64, base int) string

This method takes an int64 and a base from which the number will be converted. Here is an example showing how to use that.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	a := 1234
	
	fmt.Println(strconv.FormatInt(int64(a), 10))     // 1234
}

Since we initialized a as an in int but not an int64 it needs to be converted using simple typecast.

Using the Sprintf method

The Sprintf method from the fmt package can be used to format an integer to a string.

package main

import (
	"fmt"
)

func main() {
	a := 1234
	
	// format the string
	s := fmt.Sprintf("The integer is: %d", a)
	
	fmt.Println(s)             // The integer is: 1234
}

We must store the returned string from the method. The string can be formatted in any way defined by the user.

The naive conversion although work is not a correct way of converting integers to a string. The strconv package provides the easiest ways of doing conversions. The Sprintf function is to be used when we want to format the string in a more defined way.