Go中int、float、string的相互轉換


引用

// 推薦一個更加強大的轉換庫: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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM