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 supports the standard arithmetic operators: (Addition, Subtraction, Multiplication, Division,Remainder)
Naming Conventions for Golang Functions
Creating a Struct Instance Using a Struct Literal
Golang program for implementation of Rabin-Karp
Example: How to use ReadAtLeast from IO Package in Golang?
How do you handle HTTP server health checks in Go?
Most Helpful This Week
How to check if a string contains a white space in Golang?How to use a mutex to define critical sections of code and fix race conditions?Find element in a slice and move it to first position?Select single argument from all arguments of variadic functionReplace any non-alphanumeric character sequences with a dash using RegexRegular expression to validate email addressConvert Int data type to Int16 Int32 Int64Strip all white spaces, tabs, newlines from a stringHow to use for and foreach loop?Golang Get current Date and Time in EST, UTC and MST?