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
Golang Functions Returning Multiple ValuesHow To Make HTTP Requests in Go?Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.Strip all white spaces, tabs, newlines from a stringHow To Make an HTTP Server in Golang?Different ways to convert Byte Array into StringCatch values from GoroutinesHow to check if a string contains a white space in Golang?Convert Int data type to Int16 Int32 Int64Golang String Concatenation