Golang 保留一位小数: 使用 fmt 和 strconv 实现
Golang 保留一位小数:使用 fmt 和 strconv
在 Golang 中,您可以使用 'fmt.Printf' 函数或 'strconv.FormatFloat' 函数来控制浮点数的小数位数,将 float64 类型数据保留一位小数。
使用 fmt.Printf 函数
使用 'fmt.Printf' 函数,您可以使用 '%.1f' 的格式化字符串来保留一位小数。
以下是示例代码:
package main
import 'fmt'
func main() {
num := 3.14159
fmt.Printf('%.1f
', num)
}
输出结果为:'3.1'
使用 strconv.FormatFloat 函数
使用 'strconv.FormatFloat' 函数,您可以将浮点数转换为字符串,并指定小数位数。
以下是示例代码:
package main
import (
'fmt'
'strconv'
)
func main() {
num := 3.14159
str := strconv.FormatFloat(num, 'f', 1, 64)
fmt.Println(str)
}
输出结果为:'3.1'
希望这些代码示例能够帮助您在 Golang 中轻松地将 float64 类型数据保留一位小数!
原文地址: https://www.cveoy.top/t/topic/fzvf 著作权归作者所有。请勿转载和采集!