Sprintf可以将其他类型转换成字符串
1.1将int转换字符串
Sprintf转换int到字符串,%d
fmt.Sprintf("%d",12)
代码块
package main
import (
"fmt"
)
func main(){
a := fmt.Sprintf("%d",12)
fmt.Println(a)
fmt.Printf("%T",a)
}
运行
[root@www.linuxea.com /opt/Golang/work2]# go run fmt.go
12
string
1.2float浮点数转换为字符串
Sprintf转换float到字符串,%f
fmt.Sprintf("%f",12.2)
代码块
package main
import (
"fmt"
)
func main(){
a := fmt.Sprintf("%f",12.2)
fmt.Println(a)
fmt.Printf("%T",a)
}
运行
[root@www.linuxea.com /opt/Golang/work2]# go run fmt2.go
12.200000
string
1.3FormatBool布尔转换字符串
将bool转换字符串
strconv.FormatBool(false)
代码块
package main
import (
"fmt"
"strconv"
)
func main(){
a := strconv.FormatBool(false)
fmt.Printf("%T,%v",a,a)
}
运行
[root@www.linuxea.com /opt/Golang/work2]# go run fmt3.go
string,false
1.4 Itoa将int类型转换为字符串
将int类型转换为字符串
strconv.Itoa(123)
代码块
package main
import (
"fmt"
"strconv"
)
func main(){
a := strconv.Itoa(123)
fmt.Printf("%T,%v",a,a)
}
运行
[root@www.linuxea.com /opt/Golang/work2]# go run fmt4.go
string,123
1.5 FormatInt进制类型转换字符串
123转换10进制
strconv.FormatInt(123,10)
代码块
package main
import (
"fmt"
"strconv"
)
func main(){
a := strconv.FormatInt(123,10)
fmt.Printf("%T,%v",a,a)
}
运行
[root@www.linuxea.com /opt/Golang/work2]# go run fmt5.go
string,123
- 123转换16进制
package main
import (
"fmt"
"strconv"
)
func main(){
a := strconv.FormatInt(123,16)
fmt.Printf("%T,%v",a,a)
}
[root@www.linuxea.com /opt/Golang/work2]# go run fmt5.go
string,7b
- 123转换8进制
package main
import (
"fmt"
"strconv"
)
func main(){
a := strconv.FormatInt(123,8)
fmt.Printf("%T,%v",a,a)
}
[root@www.linuxea.com /opt/Golang/work2]# go run fmt5.go
string,173
1.6 FormatFloat转换字符串
指定一个十进制或者科学记数法,‘E’是科学计数法,如果是转换10进制这里写'f',-1精度,64是float64类型
strconv.FormatFloat(10.11,'E',-1,64)
代码块
package main
import (
"fmt"
"strconv"
)
func main(){
a := strconv.FormatFloat(10.11,'E',-1,64)
fmt.Printf("%T,%v",a,a)
}
运行
[root@www.linuxea.com /opt/Golang/work2]# go run fmt5.go
string,1.011E+01