Go

字符串和数值类型转换

 func testConvert() { 
// 测试 int 和 string(decimal) 互相转换的函数     
// https://yourbasic.org/golang/convert-int-to-string/     
  // int -> string     
sint := strconv.Itoa(97)     
fmt.Println(sint, sint == "97")     
// byte -> string     
bytea := byte(1)     
bint := strconv.Itoa(int(bytea))     
fmt.Println(bint)     
// int64 -> string     
sint64 := strconv.FormatInt(int64(97), 10)     
fmt.Println(sint64, sint64 == "97")     
// int64 -> string (hex) ,十六进制     
sint64hex := strconv.FormatInt(int64(97), 16)     
fmt.Println(sint64hex, sint64hex == "61")     
// string -> int      Atoi 是 Ascii to Integer 的缩写 
_int, _ := strconv.Atoi("97")     
fmt.Println(_int, _int == int(97))     
// string -> int64     
_int64, _ := strconv.ParseInt("97", 10, 64)     
fmt.Println(_int64, _int64 == int64(97))     
// https://stackoverflow.com/questions/30299649/parse-string-to-specific-type-of-int-int8-int16-int32-int64     
// string -> int32,注意 parseInt 始终返回的是 int64,所以还是需要 int32(n) 强转一下     
_int32, _ := strconv.ParseInt("97", 10, 32)     
fmt.Println(_int32, int32(_int32) == int32(97))     
// int32 -> string, https://stackoverflow.com/questions/39442167/convert-int32-to-string-in-golang     
i := 42     
strconv.FormatInt(int64(i), 10) 
// fast     strconv.Itoa(int(i))            
// fast     fmt.Sprint(i)                   
// slow     
// int -> int64 ,不会丢失精度     
var n int = 97     
fmt.Println(int64(n) == int64(97))     
// string -> float32/float64  https://yourbasic.org/golang/convert-string-to-float/     
f := "3.14159265"     
if s, err := strconv.ParseFloat(f, 32); err == nil {         
fmt.Println(s) // 3.1415927410125732     
}     
if s, err := strconv.ParseFloat(f, 64); err == nil {         
fmt.Println(s) // 3.14159265     
} 
} 

发表评论