Different ways for Integer to String Conversions
Like most modern languages, Golang includes Integer as a built-in type. Let's take an example, you may have a variable that contains a Integer value and you want to convert it into String. In order to convert Integer value into String type in Golang, you can use the following methods.
FormatInt() Method
You can use the strconv package's FormatInt() function to convert the int into an string value. 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.
Syntax
func FormatInt(i int64, base int) string
Example
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
var i int64 = 125
fmt.Println(reflect.TypeOf(i))
fmt.Println(i)
var s string = strconv.FormatInt(i, 10)
fmt.Println(reflect.TypeOf(s))
fmt.Println("Base 10 value of s:", s)
s = strconv.FormatInt(i, 8)
fmt.Println("Base 8 value of s:", s)
s = strconv.FormatInt(i, 16)
fmt.Println("Base 16 value of s:", s)
s = strconv.FormatInt(i, 32)
fmt.Println("Base 32 value of s:", s)
}
Output
int64
125
string
Base 10 value of s: 125
Base 8 value of s: 175
Base 16 value of s: 7d
Base 32 value of s: 3t
fmt.Sprintf() Method
Sprintf formats according to a format specifier and returns the resulting string. Here, a is of Interface type hence you can use this method to convert any type to string.
Syntax
func Sprintf(format string, a ...interface{}) string
Example
package main
import (
"fmt"
"reflect"
)
func main() {
b := 1225
fmt.Println(reflect.TypeOf(b))
s := fmt.Sprintf("%v", b)
fmt.Println(s)
fmt.Println(reflect.TypeOf(s))
}
Output
int
1225
string
Most Helpful This Week
Go program to find SRV service record of a domain
Golang program for implementation of Floyd–Warshall Algorithm
Golang Web Server Example
Interface Accepting Address of the Variable in Golang
Golang program for implementation of Binary Search
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
Most Helpful This Week
How to trim leading and trailing white spaces of a string in Golang?How to import and alias package names?Example to use Weekday and YearDay functionHow to play and pause execution of goroutine?How to create a photo gallery in Go?How can we reverse a simple string in Go?Catch values from GoroutinesHow to verify a string only contains letters, numbers, underscores, and dashes in Golang?Simple function with return value in GolangRegular expression to extract numbers from a string in Golang