ZetCode

Go int to string

last modified October 30, 2026 Go 1.27

In this article we show how to convert integers to strings in Go. The conversion is not a cast: a numeric value is turned into its decimal (or other base) representation, which is a string of characters.

Three functions cover almost every case:

All examples in this article were compiled and run with Go 1.27.0.

Converting an int with strconv.Itoa

strconv.Itoa takes an int and returns its base-10 representation. The name stands for integer to ASCII, and the function is equivalent to FormatInt(int64(i), 10).

func Itoa(i int) string

That is the signature of the function. It cannot fail, because every integer has a decimal representation.

main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {

    apples := 6

    n := strconv.Itoa(apples)
    msg := "There are " + n + " apples"

    fmt.Println(msg)
    fmt.Printf("%T -> %T\n", apples, n)
}

The result of Itoa is an ordinary string, so it can be concatenated with the surrounding text. The types printed on the second line confirm that the variable changed from int to string.

$ go run main.go
There are 6 apples
int -> string

Negative numbers and the limits of int

Itoa handles the sign and the full range of the platform int type. On a 64-bit platform that range is -9223372036854775808 to 9223372036854775807.

main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {

    vals := []int{0, -7, -9223372036854775808, 9223372036854775807}

    for _, v := range vals {
        s := strconv.Itoa(v)
        fmt.Printf("%d has %d characters: %q\n", v, len(s), s)
    }
}

The minus sign is part of the string, so the smallest value needs 20 characters while the largest needs 19. len counts bytes; for digits and the sign that is the same as the number of characters.

$ go run main.go
0 has 1 characters: "0"
-7 has 2 characters: "-7"
-9223372036854775808 has 20 characters: "-9223372036854775808"
9223372036854775807 has 19 characters: "9223372036854775807"

Converting int64 and uint64 with FormatInt and FormatUint

Itoa accepts only int. Values of other integer types must be widened explicitly and passed to strconv.FormatInt or strconv.FormatUint. Both take the base as a second argument.

func FormatInt(i int64, base int) string
func FormatUint(i uint64, base int) string

The base must be between 2 and 36; the digits above nine are the letters a to z. A base outside that range causes a panic.

main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {

    var fileSize int64 = 1544466212
    var i8 int8 = -128
    var u32 uint32 = 4000000000
    var u64 uint64 = 18446744073709551615

    fmt.Println(strconv.FormatInt(fileSize, 10))
    fmt.Println(strconv.FormatInt(int64(i8), 10))
    fmt.Println(strconv.FormatUint(uint64(u32), 10))
    fmt.Println(strconv.FormatUint(u64, 10))
}

The conversions int64(i8) and uint64(u32) widen the values without changing them, so the printed numbers match the originals. The uint64 case shows a value that does not fit into int64.

$ go run main.go
1544466212
-128
4000000000
18446744073709551615

Choosing a base

The same value can be rendered in any base. Bases 2, 8, 16 and 36 are the ones that appear most often: binary for bit masks, octal for file modes, hexadecimal for hashes and identifiers, and base 36 for short alphanumeric codes.

main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {

    val := int64(255)

    for _, base := range []int{2, 8, 10, 16, 36} {
        fmt.Printf("base %-2d: %s\n", base, strconv.FormatInt(val, base))
    }
}

The loop prints the same 255 in five notations. FormatInt does not add any prefix: every result is plain digits of the chosen base. The 0x prefix in the next section comes from the # flag of fmt, which strconv does not offer.

$ go run main.go
base 2 : 11111111
base 8 : 377
base 10: 255
base 16: ff
base 36: 73

Formatting with fmt.Sprintf

fmt.Sprintf formats according to a verb and returns the result as a string. The %d verb prints an integer in base ten, while %x, %o and %b print it in hexadecimal, octal and binary.

main.go
package main

import "fmt"

func main() {

    n := 42

    fmt.Printf("%d %05d %+d\n", n, n, n)
    fmt.Printf("%x %X %#x %o %b\n", n, n, n, n, n)
    fmt.Printf("[%8d] [%-8d]\n", n, n)

    fmt.Println(fmt.Sprintf("port %d, mask %#x", n, n))
}

The width and flag options are the reason to prefer Sprintf over Itoa: zero padding, explicit signs, prefixes and column alignment are all available without extra code. The last line shows the function used only to build a string.

$ go run main.go
42 00042 +42
2a 2A 0x2a 52 101010
[      42] [42      ]
port 42, mask 0x2a

The string(int) pitfall

Writing string(n) for an integer does not produce the decimal digits. The conversion reinterprets the number as a Unicode code point and returns a one-character string.

main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {

    n := 65

    wrong := string(n)
    right := strconv.Itoa(n)

    fmt.Printf("%q\n", wrong)
    fmt.Printf("%q\n", right)
    fmt.Println(len(wrong), len(right))
}

65 is the code point of the letter A, so the first value is the string "A" and not "65". The compiler accepts the conversion without a warning, which makes this mistake easy to miss; static checkers flag it as stringintconv.

$ go run main.go
"A"
"65"
1 2

Appending to a byte slice with AppendInt

strconv.AppendInt appends the digits to an existing byte slice and returns the extended slice. It avoids the allocation that Itoa performs for every call, which matters when many numbers are written in a row.

main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {

    buf := make([]byte, 0, 32)

    for _, n := range []int{10, 20, 30} {
        buf = strconv.AppendInt(buf, int64(n), 10)
        buf = append(buf, ',')
    }

    fmt.Printf("%q\n", buf)
    fmt.Println(len(buf), cap(buf))
}

The buffer keeps its capacity of 32 bytes, so the whole sequence is built without growing the underlying array. %q is used because the slice holds raw bytes rather than a string.

$ go run main.go
"10,20,30,"
9 32

Building a comma-separated list

A strings.Builder collects text without reallocating for every write. Combined with Itoa it produces a readable list of numbers without a trailing separator.

main.go
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {

    var sb strings.Builder
    sb.Grow(32)

    nums := []int{3, 1, 4, 1, 5}

    for i, n := range nums {
        if i > 0 {
            sb.WriteString(", ")
        }
        sb.WriteString(strconv.Itoa(n))
    }

    fmt.Println(sb.String())
}

The separator is written before every element except the first one, so the result has no trailing comma. This is the same pattern that strings.Join uses internally, but it works when the elements are not strings yet.

$ go run main.go
3, 1, 4, 1, 5

Converting back with strconv.Atoi

The reverse operation is strconv.Atoi, which parses a base-10 string into an int. It returns an error for malformed input and for values outside the range of int.

main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {

    inputs := []string{"42", "-7", " 42", "4.2", "99999999999999999999"}

    for _, s := range inputs {

        n, err := strconv.Atoi(s)
        fmt.Printf("%-22q n=%-3d err=%v\n", s, n, err)
    }
}

Leading spaces, decimal points and overflow are all rejected. On failure Atoi returns 0 or the clamped limit, and the error describes both the cause and the offending input.

$ go run main.go
"42"                   n=42  err=<nil>
"-7"                   n=-7  err=<nil>
" 42"                  n=0   err=strconv.Atoi: parsing " 42": invalid syntax
"4.2"                  n=0   err=strconv.Atoi: parsing "4.2": invalid syntax
"99999999999999999999" n=9223372036854775807 err=strconv.Atoi: parsing "99999999999999999999": value out of range

Implementing a String method

A type that implements String() string is printed through that method by every fmt verb. This is the usual place where integers are converted for display.

main.go
package main

import (
    "fmt"
    "strconv"
)

type Temperature struct {
    Celsius float64
}

func (t Temperature) String() string {
    return strconv.FormatFloat(t.Celsius, 'f', 1, 64) + " °C"
}

func main() {

    t := Temperature{21.456}

    fmt.Println(t)
    fmt.Printf("%v|%s\n", t, t)
}

FormatFloat takes the format byte, the number of digits after the point and the bit size, just as FormatInt takes the base. The digit 1 is rounded to 21.5.

$ go run main.go
21.5 °C
21.5 °C|21.5 °C

Which function to use

The choice follows from the type and the required notation:

TaskFunction
int, base 10strconv.Itoa
int64 or another widthstrconv.FormatInt
uint64 or another unsigned widthstrconv.FormatUint
padding, prefixes, alignmentfmt.Sprintf
many numbers in a bufferstrconv.AppendInt

Itoa is a thin wrapper around FormatInt; there is no performance difference worth measuring between the two.

Source

Go strconv package - reference

In this article we have converted integers to strings with strconv.Itoa, strconv.FormatInt, strconv.FormatUint, fmt.Sprintf and strconv.AppendInt, and we have parsed them back with strconv.Atoi.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.