为了将整数变量作为字符串获取,Go 提供了strconv包,该包具有返回 int 变量的字符串表示形式的方法。没有什么像整数变量被转换为字符串变量一样,相反,您必须将整数值作为字符串存储在字符串变量中。以下是用于将整数转换为字符串的函数:
1. strconv.Itoa():将一个int转换为一个十进制字符串。
// s == "60"
s := strconv.Itoa(60)
2. strconv.FormatInt():在给定的基数中格式化一个int64。
var n int64 = 60
s := strconv.FormatInt(n, 10) // s == "60" (decimal)
s := strconv.FormatInt(n, 16) // s == "3C" (hexadecimal)
3. strconv.FormatUint():返回给定基数中x的字符串表示,即2 <= base <= 36。
fmt.Println(strconv.FormatUint(60, 2)) // 111100 (binary)
fmt.Println(strconv.FormatUint(60, 10)) // 60 (decimal)
示例 1:
package main
import (
"fmt"
"strconv"
)
func main() {
var var_int int
var_int = 23
// Itoa() is the most common
// conversion from int to string.
s1 := strconv.Itoa(var_int)
fmt.Printf("%T %v\n", s1, s1)
// format 23 int base 10 -> 23
s2 := strconv.FormatInt(int64(var_int), 10)
fmt.Printf("%T %v\n", s2, s2)
// return string representation
// of 23 in base 10 -> 23
s3 := strconv.FormatUint(uint64(var_int), 10)
fmt.Printf("%T %v\n", s3, s3)
// concatenating all string->s1,s2 and s3.
fmt.Println("Concatenating all strings: ", s1+s2+s3)
}
输出:
string 23
string 23
string 23
Concatenating all strings: 232323
示例 2:
package main
import (
"fmt"
"strconv"
)
func main() {
var var_int int
var_int = 50
// Itoa() is the most common
// conversion from int to string.
s1 := strconv.Itoa(var_int)
fmt.Printf("%T %v\n", s1, s1)
// format 50 int base 2 ->110010
s2 := strconv.FormatInt(int64(var_int), 2)
fmt.Printf("%T %v\n", s2, s2)
// return string representation
// of 50 in base 16 -> 32
s3 := strconv.FormatUint(uint64(var_int), 16)
fmt.Printf("%T %v\n", s3, s3)
// concatenating all
// string->s1,s2 and s3.
fmt.Println("Concatenating all strings: ", s1+s2+s3)
}
输出:
string 50
string 110010
string 32
Concatenating all strings: 5011001032