当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go语言string,int,int64 ,float之间类型转换方法

Go语言string,int,int64 ,float之间类型转换方法

2017年12月08日  | 移动技术网IT编程  | 我要评论

(1)int转string

s := strconv.itoa(i)
等价于s := strconv.formatint(int64(i), 10)

(2)int64转string

i := int64(123)
s := strconv.formatint(i, 10)

第二个参数为基数,可选2~36

注:对于无符号整形,可以使用formatuint(i uint64, base int)

(3)string转int

i, err := strconv.atoi(s)

(4)string转int64

i, err := strconv.parseint(s, 10, 64)

第二个参数为基数(2~36),第三个参数位大小表示期望转换的结果类型,其值可以为0, 8, 16, 32和64,分别对应 int, int8, int16, int32和int64

(5)float相关

float转string:

v := 3.1415926535
s1 := strconv.formatfloat(v, 'e', -1, 32)//float32s2 := strconv.formatfloat(v, 'e', -1, 64)//float64

函数原型及参数含义具体可查看:https://golang.org/pkg/strconv/#formatfloat

string转float:

s := "3.1415926535"
v1, err := strconv.parsefloat(v, 32)
v2, err := strconv.parsefloat(v, 64)

 ps:go语言string、int、int64互相转换

//string到int 
int,err:=strconv.atoi(string) 
//string到int64 
int64, err := strconv.parseint(string, 10, 64) 
//int到string 
string:=strconv.itoa(int) 
//int64到string 
string:=strconv.formatint(int64,10)
//string到float32(float64)
float,err := strconv.parsefloat(string,32/64)
//float到string
string := strconv.formatfloat(float32, 'e', -1, 32)
string := strconv.formatfloat(float64, 'e', -1, 64)
// 'b' (-ddddp±ddd,二进制指数)
// 'e' (-d.dddde±dd,十进制指数)
// 'e' (-d.dddde±dd,十进制指数)
// 'f' (-ddd.dddd,没有指数)
// 'g' ('e':大指数,'f':其它情况)
// 'g' ('e':大指数,'f':其它情况)

总结

以上所述是小编给大家介绍的go语言string,int,int64 ,float之间类型转换方法,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网