基本类型转换字符串
num := 1
b := true
f := 3.1415926
str := fmt.Sprintf("%d",num)
fmt.Printf("%q\n",str)
str = fmt.Sprintf("%t",b)
fmt.Printf("%q\n",str)
str = fmt.Sprintf("%.2f",f)
fmt.Printf("%q\n",str)
str = strconv.FormatInt(int64(num),2)
fmt.Printf("%q\n",str)
str = strconv.FormatBool(b)
fmt.Printf("%q\n",str)
str = strconv.FormatFloat(float64(f),'f',3,64)
fmt.Printf("%q",str)
字符串转基本类型
str1 := "1"
str2 := "true"
str3 := "3.1415926"
n,_ := strconv.ParseInt(str1,10,0)
fmt.Printf("n type %T ,n=%d\n",n,n)
b,_ := strconv.ParseBool(str2)
fmt.Printf("b type %T ,b=%t\n",b,b)
f,_ := strconv.ParseFloat(str3,64)
fmt.Printf("f type %T, f=%f\n",f,f)
f2 := float32(f)
fmt.Printf("f2 type %T f2=%f\n",f2,f2)
字符串转byte
str := "hello go"
bytes := []byte(str)
字符串转切片(可以正常输出中文)
str = "hello 北京"
r := []rune(str)
for i:=0;i<len(r);i++{
fmt.Printf("%v ",r[i])
}
精度转换
只有相同的类型才能进行精度转换:
int int8 int16 int32 int64 float32 float64 可以使用 int() int8() int16() int32() int64() float32() float64()互相转换