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
Most Helpful This Week
How to fix race condition using Atomic Functions in Golang?Strip all white spaces, tabs, newlines from a stringExample to handle GET and POST request in GolangHow to trim leading and trailing white spaces of a string in Golang?How to check if a string contains a numbers in Golang?Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]How to copy a map to another map?How to collect information about garbage collection?Simple function with return value in GolangHow to wait for Goroutines to Finish Execution?