Convert Int to a String in Golang — GolangLearn

in this post, We’ll learn here about converting an int value to string in golang. The strconv is a module from the standard library that converts strings and integers directly. The golang has an inbuilt method that converts an integer into a string.

The Itoa() and FormatInt() function in the strconv package can be used to convert an integer to a string in Golang. Conversions to and from string representations to several other data types are supported by this module.

The golang int to string

Let’s see an example of how we can use these functions to convert an integer to an ASCII string.

Convert Integer into String

The Itoa method is used to convert an int to a string in the code below.

The Syntax: func Itoa(i int) string

Example:

package main import "fmt" import "strconv" import "reflect" func main() { n:= 5 fmt.Println(n, reflect.TypeOf(n)) str:= strconv.Itoa(n) fmt.Println(str, reflect.TypeOf(str)) }

Output :

5 int 5 string

Convert Integer into String

The FormatInt method can also be used to convert an int to a string. This is very useful method if we want to convert an integer base 10 to an ASCII string. Let's see the below example :

The Syntax: func FormatInt(i int64, base int) string

FormatInt returns the string representation of number in the given base.

Example:

package main import "fmt" import "strconv" import "reflect" func main() { n:= 5 fmt.Println(n, reflect.TypeOf(n)) str:= strconv.FormatInt(int64(n), 10) fmt.Println(str, reflect.TypeOf(str)) }

Output :

5 int 5 string

Originally published at https://www.golanglearn.com on November 12, 2021.

--

--

--

Hey, I am Parvez Alam. A software developer since 2009. I am a programming addict. I love learning and sharing knowledge. https://www.phpflow.com/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Parvez Alam

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I am a programming addict. I love learning and sharing knowledge. https://www.phpflow.com/

More from Medium

TicTacGo — An Intro to Golang

golang: NewReader vs NewBufferString

Encrypt a File using Go

Golang: Curious Case of Returning Byte Array and Conversion to Byte Slice