Conversion of string to integer, floating-point, boolean-byte
1. Use fmt.Sprintf to convert other types to string
%v indicates the value. %T indicates the data type
import (
"fmt"
"strconv"
)
var n int = 30
var m float64 = 12.34
var b bool = true
var c byte = 'a'
str1 := fmt.Sprintf("%d", n)
fmt.Printf("%v--%T\n", str1, str1) // 30--string
str2 := fmt.Sprintf("%.2f", m)
fmt.Printf("%v--%T\n", str2, str2) / / 12.34 - string
str3 := fmt.Sprintf("%t", b)
fmt.Printf("%v--%T\n", str3, str3) // true--string
str4 := fmt.Sprintf("%c", c)
fmt.Printf("%v--%T\n", str4, str4) // a--string
Copy the code
2. Use strconv to convert the type
Other types go to string
// Integer conversion
var n1 int64 = 40
str_n := strconv.FormatInt(n1, 10)
fmt.Printf("%v--%T\n", str_n, str_n) //40--string
// Float conversion
var f1 float64 = 40.3213213
str_f := strconv.FormatFloat(f1, 'f'.2.32)
fmt.Printf("%v--%T\n", str_f, str_f) / / 40.32 - string
// Boolean conversions are meaningless
var b1 bool = false
str_b := strconv.FormatBool(b1)
fmt.Printf("%v--%T\n", str_b, str_b) //false--string
//byte conversion has no meaning
var c1 byte = 'a'
str_c := strconv.FormatUint(uint64(c1), 10)
fmt.Printf("%v--%T\n", str_c, str_c) //97--string
Copy the code
String to another type
//string 转 int
var m1 = "12312321"
num, _ := strconv.ParseInt(m1, 10.64) // 10 represents the base. 64 represents the number of digits
fmt.Printf("%v--%T\n", num, num) // 12312321--int64
//string 转 flaot
var fl = "123.354543"
flo_num,_ :=strconv.ParseFloat(fl,64) //64 represents the number of digits
fmt.Printf("%v--%T\n", flo_num, flo_num) / / 123.354543 - float64
Copy the code