Go fmt float64问题

Air*_*ega 4 go gofmt

我在对 go fmt 包的菜鸟理解中遇到了一些问题

它涉及以下代码:

导入“fmt”

func main() {
    var smallFloat float64 = 0.123456789
    var bigFloat float64 = 123456789000

    fmt.Println(fmt.Sprintf("%f", smallFloat))
    fmt.Println(fmt.Sprintf("%f", bigFloat))
}
Run Code Online (Sandbox Code Playgroud)

输出是:

0.123457
123456789000.000000
Run Code Online (Sandbox Code Playgroud)

我不想使用科学记数法,所以认为 %f 适合我的需要。我可以从格式化页面(https://golang.org/pkg/fmt/)看到它说:

The default precision for %e and %f is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以使用 fmt 包来表示smallFloat 的完整十进制值,同时不在bigFloat 末尾附加6个零?

Ain*_*r-G 6

您可以strconv.FormatFloat将 prec 设置为 -1 来使用:

fmt.Println(strconv.FormatFloat(big, 'f', -1, 64))
fmt.Println(strconv.FormatFloat(small, 'f', -1, 64))
Run Code Online (Sandbox Code Playgroud)

印刷

123456789000
0.123456789
Run Code Online (Sandbox Code Playgroud)

游乐场:http://play.golang.org/p/7p8xnQ_BzE