• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

go语言怎么整型转为字符串

武飞扬头像
PHP中文网
帮助32

在实际开发中我们往往需要对一些常用的数据类型进行转换,如 string、int、int64、float 等数据类型之间的转换。

int整数转字符串

1、fmt.Sprintf

fmt 包应该是最常见的了,从刚开始学习 Golang 就接触到了,写 ‘hello, world’ 就得用它。它还支持格式化变量转为字符串。%d 代表十进制整数。

//Sprintf formats according to a format specifier and returns the resulting string.
func Sprintf(format string, a ...interface{}) string

使用示例:

str := fmt.Sprintf("%d", a)

2、strconv.Itoa

Go语言中的 strconv 包为我们提供了字符串和基本数据类型之间的转换功能。strconv 包中常用的函数包括 Atoi()、Itia()、parse 系列函数、format 系列函数、append 系列函数等。

其中Itoa()函数支持 int 类型转换成字符串

//Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string

使用示例:

func main() {
    num := 100
    str := strconv.Itoa(num)
    fmt.Printf("type:%T value:%#v\n", str, str)
}

运行结果如下所示:

学新通技术网

3、strconv.FormatInt

支持 int64 类型转换成字符串
参数 i 是要被转换的整数, base 是进制,例如2进制,支持2到36进制。

//FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters ‘a' to ‘z' for digit values >= 10.
func FormatInt(i int64, base int) string

使用示例:

str := strconv.FormatInt(a, 10)

扩展知识:字符串转int整数

1、strconv.Atoi

比较常见的方法

// Atoi returns the result of ParseInt(s, 10, 0) converted to type int.
func Atoi(s string) (int, error)

使用示例:

i,err := strconv.Atoi(a)

2、strconv.ParseInt

功能非常强大

// ParseInt interprets a string s in the given base (0, 2 to 36) and
// bit size (0 to 64) and returns the corresponding value i.
func ParseInt(s string, base int, bitSize int) (i int64, err error)
  • 参数1 数字的字符串形式

  • 参数2 数字字符串的进制 比如二进制 八进制 十进制 十六进制

  • 参数3 返回结果的bit大小 也就是int8 int16 int32 int64

使用示例:

i, err := strconv.ParseInt("123", 10, 32)

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanfieei
系列文章
更多 icon
同类精品
更多 icon
继续加载