golang float64只保留一位小数
在Go语言中,可以使用fmt.Printf函数或者strconv.FormatFloat函数来控制浮点数的小数位数。
使用fmt.Printf函数可以使用%.1f的格式化字符串来保留一位小数,示例如下:
package main
import "fmt"
func main() {
num := 3.14159
fmt.Printf("%.1f\n", num)
}
输出结果为:3.1
使用strconv.FormatFloat函数可以将浮点数转换为字符串,并指定小数位数,示例如下:
package main
import (
"fmt"
"strconv"
)
func main() {
num := 3.14159
str := strconv.FormatFloat(num, 'f', 1, 64)
fmt.Println(str)
}
输出结果为:3.1
原文地址: https://www.cveoy.top/t/topic/hNQv 著作权归作者所有。请勿转载和采集!