在 Go 语言 中,经常需要将 float 类型 转成 string 类型。Go 语言 float 转 string 可以使用 strconv 包或者 fmt 包里面的相关 函数。
str := strconv.FormatFloat(f float64, fmt byte, prec, bitSize int)
参数 | 描述 |
---|---|
str | 将 float 转换成的字符串。 |
f | 需要转换的 float64 类型的变量。 |
fmt | 使用 f 表示不使用指数的形式。 |
prec | 保留几位小数。 |
bitSize | 如果为 32,表示是 float32 类型,如果是 64,表示是 float64 类型。 |
我们使用了 strconv.FormatFloat 实现了将 float 类型的变量 f,转换了字符串类型的变量 str。
strconv.FormatFloat 函数的第一个参数,只能接受 float64 类型的变量。因此,如果需要将 float32 类型转成 string,需要先将 float32 转成 float64。
str := fmt.Sprintf("%f", floatVar)
参数 | 描述 |
---|---|
str | 转换成字符串后的值。 |
floatVar | 需要转换的 float 类型的变量。 |
我们使用 fmt.Sprintf 实现了将 float 类型的变量 floatVar 转成了字符串类型。
使用 strconv 包,实现 golang float 转 string
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println("Hello 嗨客网(www.haicoder.net)")
//Golang 实现 float32 转 string
var score float32 = 99.9
strScore := strconv.FormatFloat(float64(score), 'f', 10, 32)
fmt.Println("StrScore = ", strScore)
//Golang 实现 float64 转 string
var km = 9900.10
strKm := strconv.FormatFloat(km, 'f', 1, 64)
fmt.Println("StrKm = ", strKm)
}
程序运行后,控制台输出如下:
首先,我们定义了一个 float32 类型的变量,接着使用 strconv 实现了将 float32 类型转成 string 类型,因为 strconv.FormatFloat 函数第一个参数只能接受 float64 类型,所以我们首先使用 强制类型转换 将 float32 类型转成 float64 类型,并且保留了十位小数。
接着,我们定义了一个 float64 类型的变量,直接使用 strconv 实现了将 float64 类型转成 string 类型,并且保留一位小数。
使用 fmt 包,实现 golang float 转 string
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello 嗨客网(www.haicoder.net)")
//Golang 实现 float32 转 string
var score float32 = 99.9
strScore := fmt.Sprintf("%f", score)
fmt.Println("StrScore = ", strScore)
//Golang 实现 float64 转 string
var km = 9900.10
strKm := fmt.Sprintf("%.5f", km)
fmt.Println("StrKm = ", strKm)
}
程序运行后,控制台输出如下:
首先,我们定义了一个 float32 类型的变量,接着使用 fmt.Sprintf 实现了将 float32 类型转成 string 类型。
接着,我们定义了一个 float64 类型的变量,直接使用 fmt.Sprintf 实现了将 float64 类型转成 string 类型,并且保留五位小数,fmt.Sprintf 函数的第一个参数 %.Nf 表示保留 N 位小数。
在 Go 语言中,经常需要将 float 类型转成 string 类型。Go 语言 float 转 string 可以使用 strconv 包或者 fmt 包里面的相关函数。