Golang Int To String Conversion Example
Go (Golang) provides string and integer conversion directly from a package coming from the standard library - strconv
.
In order to convert an integer value to string in Golang we can use the FormatInt
function from the strconv
package.
func FormatInt(i int64, base int) string
FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters ‘a’ to ‘z’ for digit values >= 10.
So what we need is just the integer value and what base of the given integer is. There is a shorter function which we can use if we want to convert an integer base 10 to an ASCII string.
The function is Itoa
from the strconv
package.
func Itoa(i int) string
Itoa is equivalent to FormatInt(int64(i), 10).
Let’s see an example on how we can use these functions to convert an integer to an ASCII string
package main
import (
"fmt"
"strconv"
)
func main() {
i := 10
s1 := strconv.FormatInt(int64(i), 10)
s2 := strconv.Itoa(i)
fmt.Printf("%v, %v\n", s1, s2)
}
As you can see the result is exactly the same. The expected output from the above snippet is as follows
10, 10