Different Ways to Convert an Integer Variable to String in Golang
Integer variable cannot be directly convert into String variable. In order to convert string to integer type in Golang , you have store value of integer variable as string in string variable. For this, we are using strconv and fmt package functions.
1. Itoa() Function: The Itoa stands for Integer to ASCII and returns the string representation of integer with base 10.
Syntax:
func Itoa(i int) string
Example : Convert an integer variable into String using strconv.Itoa() function.
// Go program to illustrate
// How to convert integer
// variable into String
package main
import (
"fmt"
"strconv"
)
//Main Function
func main() {
i := 32
s := strconv.Itoa(i)
fmt.Printf("Type : %T \nValue : %v\n", s, s)
}
Output:
Type : string Value : 32
2. FormatInt() Function: The FormatInt is used to represents the string of integer value with base [2,36]. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
Syntax:
func FormatInt(i int64, base int) string
Example : Convert an integer variable into String using strconv.FormatInt() function.
// Go program to illustrate
// How to convert integer
// variable into String
package main
import (
"fmt"
"strconv"
)
//Main Function
func main() {
i := -32
s := strconv.FormatInt(int64(i) , 7)
fmt.Printf("Type : %T \nValue : %v\n", s, s)
}
Output:
Type : string Value : -44
3. FormatUint() Function: The FormatUint is used to represents the string of integer value with base [2,36]. The result uses the lower-case letters 'a' to 'z' for digit values >= 10. It is similar to FormatInt but the difference is that uint64 is the type of integer value.
Syntax:
func FormatUint(i uint64, base int) string
Example : Convert an integer variable into String using strconv.FormatUint() function.
// Go program to illustrate
// How to convert integer
// variable into String
package main
import (
"fmt"
"strconv"
)
//Main Function
func main() {
i := 32
s := strconv.FormatUint(uint64(i) , 7)
fmt.Printf("Type : %T \nValue : %v\n", s, s)
}
Output:
Type : string Value : 44
4. Sprintf() Function: The Sprintf is used to represents the string of integer value by formatting according to a format specifier and returns the resulting string.
Syntax:
func Sprintf(format string, a ...interface{}) string
Example : Convert an integer variable into String using fmt.Sprintf() function.
// Go program to illustrate
// How to convert integer
// variable into String
package main
import (
"fmt"
)
//Main Function
func main() {
i := 32
s := fmt.Sprintf("%d", i)
fmt.Printf("Type : %T \nValue : %v\n", s, s)
}
Output:
Type : string Value : 32