Golang strconv.FormatFloat
最后修改于 2025 年 4 月 20 日
本教程将解释如何在 Go 中使用 strconv.FormatFloat 函数。我们将通过实际示例介绍浮点数到字符串转换的基础知识。
strconv.FormatFloat 函数将浮点数转换为字符串。它通过各种选项提供对格式的精确控制。
FormatFloat 接受四个参数:浮点值、格式字节、精度和 bitSize。它返回浮点数的格式化字符串表示。
基本的 strconv.FormatFloat 示例
strconv.FormatFloat 最简单的用法是将浮点数转换为字符串。这里我们用默认格式演示基本转换。
package main
import (
"fmt"
"strconv"
)
func main() {
f := 123.456
s := strconv.FormatFloat(f, 'f', -1, 64)
fmt.Printf("Float %f converted to string '%s'\n", f, s)
}
我们使用 'f' 格式将浮点数 123.456 转换为字符串。精度 -1 表示使用必需的最少数字位数。64 指定 float64 类型。
不同的格式选项
strconv.FormatFloat 支持多种格式选项。此示例展示了不同格式说明符的实际应用。
package main
import (
"fmt"
"strconv"
)
func main() {
f := 123.456
fmt.Println("'f' format:", strconv.FormatFloat(f, 'f', 2, 64))
fmt.Println("'e' format:", strconv.FormatFloat(f, 'e', 3, 64))
fmt.Println("'E' format:", strconv.FormatFloat(f, 'E', 4, 64))
fmt.Println("'g' format:", strconv.FormatFloat(f, 'g', -1, 64))
fmt.Println("'G' format:", strconv.FormatFloat(f, 'G', 5, 64))
}
我们演示了 'f'(十进制)、'e'(科学计数法)、'E'(大写科学计数法)、'g'(紧凑)和 'G'(大写紧凑)格式。每种格式都有不同的输出。
控制精度
精度参数控制显示的位数。此示例显示精度如何影响不同的格式类型。
package main
import (
"fmt"
"strconv"
)
func main() {
f := 123.456789
for i := 0; i <= 6; i++ {
fmt.Printf("Precision %d: %s\n",
i, strconv.FormatFloat(f, 'f', i, 64))
}
}
我们将精度从小数点后 0 位逐渐增加到 6 位。更高的精度值会显示更多数字,并在必要时进行四舍五入。
科学计数法格式
科学计数法对于非常大或非常小的数字很有用。此示例演示了科学计数法格式选项。
package main
import (
"fmt"
"strconv"
)
func main() {
small := 0.0000123456
large := 1234567890.12345
fmt.Println("Small number:", strconv.FormatFloat(small, 'e', -1, 64))
fmt.Println("Large number:", strconv.FormatFloat(large, 'E', 3, 64))
}
我们使用 'e' 格式化一个非常小的数字,并使用 'E' 格式化一个大数字。科学计数法使这些值更易读、更紧凑。
使用 'g' 进行紧凑格式化
'g' 格式会自动选择十进制或科学计数法。此示例说明它如何产生紧凑的输出。
package main
import (
"fmt"
"strconv"
)
func main() {
numbers := []float64{123.456, 123456789.0, 0.0000123456}
for _, num := range numbers {
fmt.Println(strconv.FormatFloat(num, 'g', -1, 64))
}
}
'g' 格式为每个数字选择最合适的表示形式。中等大小的数字使用十进制,而非常大/小的数字使用科学计数法。
处理特殊的浮点值
strconv.FormatFloat 正确处理 Infinity 和 NaN 等特殊浮点值。此示例演示了它们的字符串表示。
package main
import (
"fmt"
"math"
"strconv"
)
func main() {
posInf := math.Inf(1)
negInf := math.Inf(-1)
nan := math.NaN()
fmt.Println("Positive Infinity:", strconv.FormatFloat(posInf, 'f', -1, 64))
fmt.Println("Negative Infinity:", strconv.FormatFloat(negInf, 'g', -1, 64))
fmt.Println("NaN:", strconv.FormatFloat(nan, 'e', -1, 64))
}
特殊浮点值被转换为其标准的字符串表示。Infinity 变为 "+Inf" 或 "-Inf",而 NaN 变为 "NaN"。
实际示例:CSV 数据格式化
这个实际示例展示了如何使用 FormatFloat 以受控精度准备要输出到 CSV 的浮点数据。
package main
import (
"fmt"
"strconv"
)
type Measurement struct {
Name string
Value float64
}
func main() {
data := []Measurement{
{"Temperature", 23.4567},
{"Humidity", 45.6},
{"Pressure", 1013.2468},
}
for _, m := range data {
fmt.Printf("%s,%s\n",
m.Name, strconv.FormatFloat(m.Value, 'f', 2, 64))
}
}
我们将测量值格式化为 2 位小数,以实现一致的 CSV 输出。这确保了生成的数据文件具有统一的精度。
来源
本教程通过实际示例,介绍了 Go 中 strconv.FormatFloat 函数在各种场景下的浮点数到字符串转换。