GolangNote

Golang笔记

使用 strconv 来把数字转字为符串

Permalink

使用 strconv 来把数字转字为符串。

Go: strconv
1
2
3
4
5
6
7
8
9
10
11
package main

import (
    "strconv"
    "fmt"
)

func main() {
    t := strconv.Itoa(123)
    fmt.Println(t)
}

strconv 其它有用函数

字符串转为整型

Go: strconv字符串转为整型函数
1
2
3
func Atoi(s string) (i int, err error)
func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseUint(s string, base int, bitSize int) (n uint64, err error)

base 指定进制(2到36),如果 base 为 0,则会从字符串前置判断,”0x”是 16 进制,”0” 是 8 进制,否则是 10 进制;

bitSize 指定结果必须能无溢出赋值的整数类型,0、8、16、32、64 分别代表 int、int8、int16、int32、int64;

整型转为字符串

Go: strconv整型转为字符串函数
1
2
3
func FormatUint(i uint64, base int) string    // 无符号整型转字符串
func FormatInt(i int64, base int) string    // 有符号整型转字符串
func Itoa(i int) string

字符串和浮点数之间的转换

Go: 字符串和浮点数之间的转换
1
2
3
func ParseFloat(s string, bitSize int) (f float64, err error)
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
func AppendFloat(dst []byte, f float64, fmt byte, prec int, bitSize int)

prec控制精度(排除指数部分)

字符串和布尔值之间的转换

Go: strconv字符串和布尔值之间的转换函数
1
2
3
4
5
6
7
8
// 接受 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False 等字符串;
// 其他形式的字符串会返回错误
func ParseBool(str string) (value bool, err error)
// 直接返回 "true" 或 "false"
func FormatBool(b bool) string
// 将 "true" 或 "false" append 到 dst 中
// 这里用了一个 append 函数对于字符串的特殊形式:append(dst, "true"...)
func AppendBool(dst []byte, b bool)

本文网址: https://golangnote.com/topic/96.html 转摘请注明来源

Related articles

groupcache 使用入门

groupcache 是 memcached 作者 Brad Fitzpatrick 用 Go 语言编写的缓存及缓存过滤库,作为 memcached 许多场景下的替代版本。...

golang Selenium WebDriver 使用记录

Selenium WebDriver 直接通过浏览器自动化的本地接口来调用浏览器,以达到模拟浏览器行为的操作,如点击、选择、鼠标移动等。下面是记录个人使用golang 驱动的记录。...

golang snappy 的使用场合

google 自家的 snappy 压缩优点是非常高的速度和合理的压缩率。压缩率比 gzip 小,CPU 占用小。...

Write a Comment to "使用 strconv 来把数字转字为符串"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms