gpt4 book ai didi

go - 在 Golang 中以最小宽度 float 到字符串

转载 作者:IT王子 更新时间:2023-10-29 01:54:44 24 4
gpt4 key购买 nike

我正在尝试使用 fmt.Printf 打印一个最小宽度为 3 的 float

fmt.Printf("%3f", float64(0))

应该打印 0.00,但它却打印 0.000000如果我将精度设置为 3,它会截断该值。

基本上,我想要的是如果值为 0,它应该打印 0.00。如果值为0.045,则应打印0.045

最佳答案

这个函数应该做你想做的:

func Float2String(i float64) string {
// First see if we have 2 or fewer significant decimal places,
// and if so, return the number with up to 2 trailing 0s.
if i*100 == math.Floor(i*100) {
return strconv.FormatFloat(i, 'f', 2, 64)
}
// Otherwise, just format normally, using the minimum number of
// necessary digits.
return strconv.FormatFloat(i, 'f', -1, 64)
}

关于go - 在 Golang 中以最小宽度 float 到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40285127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com