Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > go strconv包用法

go strconv包用法举例详解

作者:争不过朝夕,又念着往昔

Go语言中strconv包实现了基本数据类型和其字符串表示的相互转换, strconv包实现了基本数据类型与其字符串表示的转换,这篇文章主要介绍了go strconv包用法的相关资料,需要的朋友可以参考下

字符串转整型

func Atoi(s string) (int, error)

s是要转换的字符串,返回值一个是转换后的int值,一个是错误,当转换成功的话error为nil。
正数负数都可以转换,超过范围、或者无法转换可以通过返回值error来分辨。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	ints1, err1 := strconv.Atoi("123456")
	fmt.Println(ints1, err1)

	ints2, err2 := strconv.Atoi("123456111111111111111111111111111111111111111111111111111111")
	fmt.Println(ints2, err2)

	ints3, err3 := strconv.Atoi("-854")
	fmt.Println(ints3, err3)

}

整型转字符串

func Itoa(i int) string

一个返回值类型为string,和Atoi不一样,Atoi有俩返回值,Itoa只有一个
正数负数都可转换

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str1 := strconv.Itoa(256)
	fmt.Println(str1)

	str2 := strconv.Itoa(-256)
	fmt.Println(str2)

	str3 := strconv.Itoa(+256)
	fmt.Println(str3)
}

字符串转布尔值

func ParseBool(str string) (bool, error)

作用是把下面的字符串转换为bool值,比如传入个1,会返回个bool类型的true,传入个0,会返回个bool类型的false

“1”, “t”, “T”, “true”, “TRUE”, “True” // true
“0”, “f”, “F”, “false”, “FALSE”, “False” // false

package main

import (
	"fmt"
	"strconv"
)

func main() {
	parseBool, err := strconv.ParseBool("1")
	fmt.Println(parseBool, err)

	b, err := strconv.ParseBool("true")
	fmt.Println(b, err)

	b2, err := strconv.ParseBool("FALSE")
	fmt.Println(b2, err)
}

布尔值转字符串

func FormatBool(b bool) string

传入一个bool值,返回一个全小写无引号的true或者false字符串

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var t bool = true
	var f bool = false
	fmt.Println(strconv.FormatBool(t))
	fmt.Println(strconv.FormatBool(f))
}

转换成 Go 字符串

func Quote(s string) string
func QuoteToASCII(s string) string

Quote 保留原始字符,非 ASCII 字符(如中文)直接输出。
QuoteToASCII 将非 ASCII 字符(如中文)转义为 Unicode 转义序列(\uXXXX)。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	fmt.Println(strconv.Quote("hello 世界"))        // 输出: "hello 世界"
	fmt.Println(strconv.QuoteToASCII("hello 世界")) // 输出: "hello \u4e16\u754c"
}

字符串转浮点数

func ParseFloat(s string, bitSize int) (float64, error)

s是要转换的字符串
bitsize是位数,必须是32或者64其中一个,表示转为为32位精度还是64位精度。
32位精度在6-7位,64位精度在15-16位

package main

import (
	"fmt"
	"strconv"
)

func main() {
	float, err := strconv.ParseFloat("3.1415926", 32)
	fmt.Println(float, err)

	float, err = strconv.ParseFloat("1.14576247456852556", 64)
	fmt.Println(float, err)
}
  1. 第一行输出:3.141592502593994(bitSize=32)
    输入字符串:“3.1415926”(7 位有效数字)。
    实际解析:
    字符串被解析为 float32 精度(约 6-7 位有效数字),但返回的是 float64 类型。
    float32 无法精确表示 3.1415926,因此发生了舍入:
    原始值 3.1415926 的二进制表示在 float32 中会被舍入为最接近的可表示值 3.141592502593994。
    为什么返回 float64?
    Go 的 ParseFloat 统一返回 float64,但数值范围受 bitSize 限制。若需 float32,需显式转换:float32(float)。
  2. 第二行输出:1.14576247456852556(bitSize=64)
    输入字符串:“1.14576247456852556”(17 位有效数字)。
    实际解析:
    字符串被解析为 float64 精度(约 15-16 位有效数字)。
    float64 能精确表示前 15-16 位,因此输出与输入几乎一致(末尾数字可能因二进制浮点表示略有差异)。

浮点数转字符串

func FormatFloat(f float64, fmt byte, prec int, bitSize int) string

f float64:要格式化的浮点数(类型必须是 float64)。
fmt byte:格式化方式,取值范围:

prec int:控制精度(小数点后的位数或科学计数法的有效数字):

bitSize int: 指定 f 的原始类型(32 或 64),影响解析时的舍入行为:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	f := 3.141592653589793

	// 1. 普通小数格式 ('f')
	fmt.Println(strconv.FormatFloat(f, 'f', 2, 64)) // 3.14
	fmt.Println(strconv.FormatFloat(f, 'f', 5, 64)) // 3.14159

	// 2. 科学计数法 ('e')
	fmt.Println(strconv.FormatFloat(f, 'e', 3, 64)) // 3.142e+00
	fmt.Println(strconv.FormatFloat(f, 'E', 3, 64)) // 3.142E+00

	// 3. 自动选择 'e' 或 'f' ('g')
	fmt.Println(strconv.FormatFloat(f, 'g', 4, 64)) // 3.142
	fmt.Println(strconv.FormatFloat(123456.0, 'g', 4, 64)) // 1.235e+05

	// 4. 二进制指数格式 ('b')
	fmt.Println(strconv.FormatFloat(f, 'b', 0, 64)) // 7074237752068736p-51

	// 5. bitSize 的影响(模拟 float32 的精度)
	f32 := float32(f)
	fmt.Println(strconv.FormatFloat(float64(f32), 'f', 5, 32)) // 3.14159 (float32 的精度)
	fmt.Println(strconv.FormatFloat(float64(f32), 'f', 10, 32)) // 3.1415927410 (float32 的精度限制)
}

字符串转复数

func ParseComplex(s string, bitSize int) (complex128, error)

s - 要转换的字符串
bitSize - 位数,必须是64或128其中之一

package main

import (
	"fmt"
	"strconv"
)

func main() {
	fmt.Println(strconv.ParseComplex("1+2i", 128))
	fmt.Println(strconv.ParseComplex("1+2j", 128))//只支持 i 作为虚部单位 
}

复数转字符串

func FormatComplex(c complex128, fmt byte, prec, bitSize int) string
package main

import (
	"fmt"
	"strconv"
)

func main() {
	fmt.Println(strconv.FormatComplex(complex(1.1, 12), 'f', 2, 128))
	fmt.Println(strconv.FormatComplex(complex(5.6, 2.8), 'b', 2, 128))
	fmt.Println(strconv.FormatComplex(complex(18.88999, 89.7), 'g', 2, 128))

}

字符串追加数据

在 Java 中,字符串与其他类型(如数字)进行拼接时,会自动将非字符串类型转换为字符串。例如:

String result = "1" + 1;  // 结果为 "11",Java 自动将数字 1 转换为字符串 "1"

但在 go 里,这种隐式类型转换是不允许的。如果尝试直接拼接字符串和数字,编译器会报错:

result := "1" + 1  // 编译错误:invalid operation: "1" + 1 (mismatched types string and int)

go 要求显式处理类型转换。如果需要将数字(如 int、float64 等)拼接到字符串中,可以使用 strconv包提供的函数(如 FormatInt、FormatFloat 等),或直接使用 fmt.Sprintf`进行格式化。

但如果高效拼接字符串和数字(避免额外分配内存),Go 的 strconv包还提供了 Append系列函数,可以直接将数字的字符串表示追加到现有的 []byte切片中,减少内存分配。

package main

import (
	"fmt"
	"strconv"
)

func main() {

	bytes := []byte("这里有一些数据:")
	bytes = strconv.AppendInt(bytes, 10, 10)
	bytes = strconv.AppendFloat(bytes, 1.2222, 'f', 2, 64)
	bytes = strconv.AppendBool(bytes, false)
	fmt.Println(string(bytes))

}

总结 

到此这篇关于go strconv包用法的文章就介绍到这了,更多相关go strconv包用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文