引用
// 推荐一个更加强大的转换库:https://github.com/spf13/cast
package main
import (
"fmt"
"strconv"
)
func main() {
// 测试 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
_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
fmt.Println("------- int32 -> string ------")
res1 := strconv.FormatInt(int64(23), 10) // fast
fmt.Println("res1>>> ",res1)
res2 := strconv.Itoa(int(23)) // fast
fmt.Println("res2>>> ",res2)
res3 := fmt.Sprint(23) // slow
fmt.Println("re3s>>> ",res3)
fmt.Println("-------------")
// 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
}
// float -> string https://yourbasic.org/golang/convert-string-to-float/
s := fmt.Sprintf("%f", 123.456)
fmt.Println("s>>> ",s)
}
另外一个转换库
https://github.com/spf13/cast