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

golang snappy 的使用场合

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

Go Modules 使用备忘

简单说 Go Modules 就是包管理,从 go1.11 开始支持,可以不需要gopath存在,环境变量`GO111MODULE`,默认为 `auto` 项目存在 `go.mod` 则使用 go module ,否则使用GOPATH 和 vendor 机制。...

bolt 使用示例

bolt 是一款高性能的key value 数据库,下面是它的使用示例:...

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

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