这个包主要用于字符串与其他类型的转换,strconv通过包内的变量获取程序运行的操作系统下int类型所占的为数strconv.IntSize一般来说几乎所以类型都可以被转换为字符串,但反过来要把字符串转为其他类型就不一定能成功了。前面我们看过了rune和strings类型的转换,现在来看数字和字符串之间的转换。
从数字类型转换到字符串,go语言提供了strconv.Itoa和steconv.FormatFloat()等函数,其中Itoa是吧十进制数转换为字符串,FormatFloat则是将64位浮点型的数字转换为字符串
strconv.FormatFloat(f float64,fmt byte ,prec int,bitsize int)string
其中fmt表示格式,prec表示精度,bitSize的值为32则表示float32 float64
反过来从字符串到数字类型,go语言也提供了一些函数,例如strconv.Atoi(s string)(i int, err error) 将字符串转换为int型,
package main
import (
"fmt"
"strconv"
)
func main() {
orig := "22aa3"
fmt.Printf("orig当前是%T类型,且操作系统是%d位\n", orig, strconv.IntSize)
num, _ := strconv.Atoi(orig) //将string转为int型
fmt.Printf("num当前是%T类型,且数值是%d\n", num, num)
// fmt.Printf("%s\n", err)
num += 5
newS := strconv.Itoa(num) //将int型转为string型
fmt.Printf("%T,%s\n", newS, newS)
}
strconv.Atoi 将string转int
strconv.Itoa 将int转string