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
Various examples of printing and formatting in Golang
React JS Count number of checkboxes are checked
Unveiling the Potential of Quantum Computing in AI: A Game Changer for Industries
Exploring Blockchain: Top 15 Real-World Use Cases in 2024
Polymorphism in Go Programming Language
How do you handle HTTP server health checks in Go?
Most Helpful This Week
Find out how many logical processors used by current processExample to handle GET and POST request in GolangSimple function with parameters in GolangHow to reads and decodes JSON values from an input stream?Closures Functions in GolangGolang String ConcatenationHow to handle HTTP Get response?Add N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-timeFind element in a slice and move it to first position?Pass different types of arguments in variadic function