Convert int to string in Go (strconv, fmt, bytes.Buffer)

Convert int to string in Go with strconv.Itoa or strconv.FormatInt, fmt.Sprintf or fmt.Fprintf to an io.Writer, and strings.Builder for custom assembly; compare with general type conversion in Go.

Published

Updated

Read time 1 min read

Reviewed byDeepak Prasad

Convert int to string in Go (strconv, fmt, bytes.Buffer)

To golang convert int to string, use the strconv package first: strconv.Itoa for int, or strconv.FormatInt(int64(n), base) for other bases. fmt.Sprintf("%d", n) is readable for mixed formatting. fmt.Fprintf writes the same representation to an io.Writer such as bytes.Buffer. For broader conversion rules, see type casting in Go.

Tested with Go 1.24 on Linux.


strconv.Itoa and strconv.FormatInt

go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	n := 42
	fmt.Println(strconv.Itoa(n))
	fmt.Println(strconv.FormatInt(int64(n), 16))
}
Output

You should see 42 then 2a.


fmt.Sprintf

go
package main

import "fmt"

func main() {
	fmt.Println(fmt.Sprintf("%d", 42))
}
Output

fmt.Fprintf to a buffer

go
package main

import (
	"bytes"
	"fmt"
)

func main() {
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "%d", 42)
	fmt.Println(buf.String())
}
Output

strings.Builder (when assembling larger text)

For many fragments, strings.Builder avoids extra copies; for a single integer, strconv.Itoa remains simpler than hand-rolling digits unless you have special formatting needs.


Summary

Prefer strconv.Itoa / FormatInt for golang convert int to string in hot paths; use fmt.Sprintf or fmt.Fprintf when the integer is part of a larger formatted message. Avoid string(int) for decimal digits—it is not the same operation.


References


Frequently Asked Questions

1. What is the fastest way to convert int to string in Go?

strconv.Itoa for int, or strconv.FormatInt for int64 with a chosen base, usually allocate less than fmt.Sprintf because they avoid parsing a format string.

2. When should I use strconv.FormatInt instead of Itoa?

When you need bases other than 10, such as hex with base 16, or when the value is already int64.

3. Can I use fmt.Fprintf to write an int into a buffer?

Yes. Pass an io.Writer such as bytes.Buffer or strings.Builder and use fmt.Fprintf(&buf, "%d", n); then read buf.String() if you used bytes.Buffer.

4. Does Go allow casting int to string with string(n)?

No. string(n) where n is an int converts a code point, not a decimal rendering. Use strconv for numeric text.

5. Where is general conversion explained?

See the guide on Go type conversion and assertions for numeric casts versus string conversions.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …