Converting an Int to a String in Go

Clive B.
jump to solution

The Problem

When using string(n) to convert an integer to a string in Go, it returns unexpected results or doesn’t compile.

This occurs because the Go type system doesn’t support direct conversion between numeric and string types. For example, the following function prints {, which is the Unicode code point value for {:

package main

func main() {
	print(string(123))
}

The Solution

The simplest and fastest way to convert integers to strings is to use the strconv.Itoa function (Itoa is short for “integer to ASCII”):

package main

import "strconv"

func main() {
	a := 123
	print(strconv.Itoa(a))
}

This prints:

123

Converting More Than Just Integers

The strconv package has all the utilities you need to convert numbers to strings and back again.

For example, you can use the FormatInt function to convert an integer to a binary string by passing in the integer and base 2:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	i := int64(123)

	fmt.Println(strconv.FormatInt(i, 2))
}

This prints:

1111011

You can also use FormatInt to convert an integer to a hexadecimal string by passing in the integer and base 16:

func main() {
	i := int64(123)

	fmt.Println(strconv.FormatInt(i, 16))
}

This prints:

7b

Alternatively, you can use the FormatFloat function to convert floats to strings:

func main() {
	f := 3.1415926535

	// Assuming a bit size of 32, convert to a string with no exponent and 3 digits of precision.
	fmt.Println(strconv.FormatFloat(f, 'f', 3, 32))
}

This prints:

3.142

String Concatenation

If you want to combine numbers and strings into a single value, you can use string concatenation.

Further Reading

Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Sentry