Sentry Answers>Go>

Converting an Int to a String in Go

Converting an Int to a String in Go

Clive B.

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

Click to Copy
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”):

Click to Copy
package main import "strconv" func main() { a := 123 print(strconv.Itoa(a)) }

This prints:

Click to Copy
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:

Click to Copy
package main import ( "fmt" "strconv" ) func main() { i := int64(123) fmt.Println(strconv.FormatInt(i, 2)) }

This prints:

Click to Copy
1111011

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

Click to Copy
func main() { i := int64(123) fmt.Println(strconv.FormatInt(i, 16)) }

This prints:

Click to Copy
7b

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

Click to Copy
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:

Click to Copy
3.142

String Concatenation

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

Further Reading

  • SentryGo Error Tracking and Performance Monitoring
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,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.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.