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.