像大多数现代语言一样,Golang 包含 Integer 作为内置类型。让我们举个例子,你可能有一个包含整数值的变量,你想把它转换为字符串。为了在Golang中将整数值转换为字符串类型,您可以使用以下方法。
FormatInt()方法
您可以使用strconv包的FormatInt()函数将 int 转换为字符串值。FormatInt 返回给定基数中i的字符串表示形式,对于2<=基数<= 36。结果使用小写字母“a”到“z”表示数字值 >= 10。
func FormatInt(i int64, base int) string
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)
}
输出
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() 方法
Sprintf根据格式说明符设置格式,并返回结果字符串。在这里,a是接口类型,因此您可以使用此方法将任何类型转换为字符串。
func Sprintf(format string, a ...interface{}) string
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))
}
输出
int
1225
string