strconv包

strconv包主要用于字符串与其他类型的转换。一般来说,几乎所有的类型都能被转换成字符串,但是从字符串转换成其他类型就不一定能成功了。

从数字类型转换到字符串,我们可以使用strconv.Itoa和strconv.FormatFloat()等函数,Itoa是把十进制数转换成字符串,FormatFloat是将64位浮点型的数字转换成字符串。

strconv.FormatFloat(f float64, fmt byte, prec int, bitSize int)

其中,fmt表示格式(其值可以是 'a', 'b', 'c'),prec表示精度,bitSize的值是32就表示float32,是64就表示float64。

从字符串到数字类型,也可以使用strconv.Atoi(s string)(int, err,error)将字符串转换为int类型,strconv.ParseFloat(s string, bitSize int)(f float64, err error)将字符串转换为float64型。这个函数会返回两个值,分别是转换后的结果(成功转换)可能出现的错误

对于多返回值的函数,可以把语句写成这样

func main() {

    str := "233"
    fmt.Printf("str当前是 %T 类型,且操作系统是%d位 \n", str, strconv.IntSize) //使用strconv.InSize获取int类型所占位数

    num, _ := strconv.Atoi(str) //使用strconv.Atoi()把字符串转换到数字类型
    fmt.Printf("num当前是%T类型,且数值是%d。\n", num, num)
    fmt.Printf("%s\n", num)

    num += 5
    newS := strconv.Itoa(num) //使用strconv.Itoa()把数字类型转换成字符串,程序输出乱码表示无法转换
    fmt.Printf("%s\n", newS)
}

/*
str当前是 string 类型,且操作系统是64位
num当前是int类型,且数值是233。
%!s(int=233)
238
*/

sunlingbot
22 声望3 粉丝

永远保持学习