# Go: Convert an Int to a String

> Convert integers to strings in Go using strconv.Itoa, plus FormatInt and FormatFloat for other bases and floating-point number conversions

**URL:** https://sentry.io/answers/converting-an-int-to-a-string-in-go/

---

## 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 `{`:

```go
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`](https://pkg.go.dev/strconv#Itoa) function (`Itoa` is short for "integer to ASCII"):

```go
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`:

```go
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`:

```go
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:

```go
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](https://sentry.io/answers/concatenating-strings-in-go/).

### Further Reading

- The [Go `strconv` package](https://pkg.go.dev/strconv) documentation

---

*Source: [sentry.io/answers/converting-an-int-to-a-string-in-go/](https://sentry.io/answers/converting-an-int-to-a-string-in-go/)*
