【发布时间】:2023-04-07 14:47:01
【问题描述】:
我正在尝试使用 fmt.Printf 打印一个最小宽度为 3 的浮点数
fmt.Printf("%3f", float64(0))
应该打印0.00,但它会打印0.000000
如果我将精度设置为 3,它会截断值。
基本上,我想要的是如果值为 0,它应该打印0.00。如果值为0.045,则应打印0.045等。
【问题讨论】:
标签: go
我正在尝试使用 fmt.Printf 打印一个最小宽度为 3 的浮点数
fmt.Printf("%3f", float64(0))
应该打印0.00,但它会打印0.000000
如果我将精度设置为 3,它会截断值。
基本上,我想要的是如果值为 0,它应该打印0.00。如果值为0.045,则应打印0.045等。
【问题讨论】:
标签: go
这个函数应该做你想做的:
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)
}
【讨论】:
使用strconv.FormatFloat,例如,像这样:
https://play.golang.org/p/wNe3b6d7p0
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(strconv.FormatFloat(0, 'f', 2, 64))
fmt.Println(strconv.FormatFloat(0.0000003, 'f', -1, 64))
}
0.00
0.0000003
有关其他格式选项和模式,请参阅链接文档。
【讨论】:
【讨论】: